dt3999 2017-01-09 16:27
浏览 35
已采纳

无法在Slim Framework控制器__construct()中执行重定向

I have an application in Slim Framework v3. There are 2 controllers, classes/FrontController.php and classes/AdminController.php.

AdminController.php is for Admin functionality (un-surprisingly!) and the FrontController.php for "public" part of the application.

Various routes have been defined in /index.php which run functions in these controllers - all normal.

What I'm trying to do is write a single piece of code (without repeating it all over) inside AdminController::__construct() such that it will redirect users to FrontController::index() if they try and access any Admin routes via URL manipulation.

The code which I have in my AdminController is like this:

public function __construct(Slim\Container $ci) {
    $this->ci = $ci;
    if (!$this->_isAdmin()) {
        return $this->ci->response->withStatus(302)->withHeader('Location', '/index');
    }
}

This doesn't seem to do anything even though $this->_isAdmin() returns false - I've even tested it by only returning false irrespective of the result the database would return under normal operation. My expectation is that it would redirect at this point, but it instead goes and loads up AdminController::index() if I try and access /admin in the browser.

I'm guessing this is something to do with the fact that the response cannot be manipulated in the constructor? But I'm lost now and not sure how to handle this. Any advice appreciated.

For information the routes in my index.php are like this:

$app->get('/', '\FrontController:index')->setName('/index');
$app->get('/admin', '\AdminController:index');
// many other routes...
  • 写回答

1条回答 默认 最新

  • download2565 2017-01-09 16:42
    关注

    You are trying to return an Response object inside an constructor. A constructor is for constructing the object, so the return value does nothing, you should either use middleware for this or make this check in every route method.

    $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);
    });
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题