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

报告相同问题?

悬赏问题

  • ¥20 求快手直播间榜单匿名采集ID用户名简单能学会的
  • ¥15 DS18B20内部ADC模数转换器
  • ¥15 做个有关计算的小程序
  • ¥15 MPI读取tif文件无法正常给各进程分配路径
  • ¥15 如何用MATLAB实现以下三个公式(有相互嵌套)
  • ¥30 关于#算法#的问题:运用EViews第九版本进行一系列计量经济学的时间数列数据回归分析预测问题 求各位帮我解答一下
  • ¥15 setInterval 页面闪烁,怎么解决
  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历