Php 无法在Slim Framework controller__构造()内执行重定向
我在Slim Framework v3中有一个应用程序。有两个控制器,Php 无法在Slim Framework controller__构造()内执行重定向,php,slim,Php,Slim,我在Slim Framework v3中有一个应用程序。有两个控制器,classes/FrontController.php和classes/AdminController.php AdminController.php用于管理功能(毫不奇怪!),而FrontController.php用于应用程序的“公共”部分 在/index.php中定义了各种路由,这些路由在这些控制器中运行函数-所有这些都是正常的 我想做的是在AdminController::u construct()中编写一段代码(不重
classes/FrontController.php
和classes/AdminController.php
AdminController.php
用于管理功能(毫不奇怪!),而FrontController.php
用于应用程序的“公共”部分
在/index.php
中定义了各种路由,这些路由在这些控制器中运行函数-所有这些都是正常的
我想做的是在AdminController::u construct()
中编写一段代码(不重复),这样,如果用户试图通过URL操作访问任何管理路由,它就会将用户重定向到FrontController::index()
AdminController中的代码如下所示:
public function __construct(Slim\Container $ci) {
$this->ci = $ci;
if (!$this->_isAdmin()) {
return $this->ci->response->withStatus(302)->withHeader('Location', '/index');
}
}
$app->get('/', '\FrontController:index')->setName('/index');
$app->get('/admin', '\AdminController:index');
// many other routes...
即使$This->\u isAdmin()
返回false,这似乎没有任何作用-我甚至通过只返回false来测试它,而不管数据库在正常操作下返回的结果如何。我的期望是,它将在此时重定向,但如果我尝试在浏览器中访问/admin
,它将转到并加载AdminController::index()
我猜这与响应不能在构造函数中操作有关?但我现在迷路了,不知道该怎么办。谢谢你的建议
有关信息,myindex.php
中的路由如下所示:
public function __construct(Slim\Container $ci) {
$this->ci = $ci;
if (!$this->_isAdmin()) {
return $this->ci->response->withStatus(302)->withHeader('Location', '/index');
}
}
$app->get('/', '\FrontController:index')->setName('/index');
$app->get('/admin', '\AdminController:index');
// many other routes...
您正在尝试在构造函数中返回响应对象。构造函数用于构造对象,因此返回值不起任何作用,您应该为此使用中间件,或者在每个路由方法中进行检查
$app->get('/admin', '\AdminController:index')->add(function($request, $response, $next) {
if(user is not admin) {
return $response->withStatus(302)->withHeader('Location', '/index');
}
return $next($request, $response);
});
您正在尝试在构造函数中返回响应对象。构造函数用于构造对象,因此返回值不起任何作用,您应该为此使用中间件,或者在每个路由方法中进行检查
$app->get('/admin', '\AdminController:index')->add(function($request, $response, $next) {
if(user is not admin) {
return $response->withStatus(302)->withHeader('Location', '/index');
}
return $next($request, $response);
});
但是,使用上述方法,您可能必须为每条路线添加类似的内容?因此,在每个路由方法中添加逻辑没有什么好处?天气肯定不是很干燥@Andy您可以使用分组的路由,请参见搜索
路由组
,您可以将中间件添加到组中,这样就不需要将其添加到每个路由中。您还可以添加一个全局中间件,然后检查启动url/admin
。或者你可以添加一个自己的,抛出一个拒绝访问的异常,然后在那里捕获它?因此,在每个路由方法中添加逻辑没有什么好处?天气肯定不是很干燥@Andy您可以使用分组的路由,请参见搜索路由组
,您可以将中间件添加到组中,这样就不需要将其添加到每个路由中。您还可以添加一个全局中间件,然后检查启动url/admin
。或者您可以添加一个自己的,抛出一个拒绝访问的异常,并在那里捕获它。