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 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?