Slimframework 3重定向在控制器中不起作用

时间:2018-10-10 04:50:34

标签: php slim slim-3

我在slim v3.11.0中遇到重定向问题。当我要求路由或中间件中的重定向时,它可以按预期工作。但是,当我从控制器调用它时,它不会重定向也不会出错。任何帮助将不胜感激!谢谢!

*参考https://www.slimframework.com/docs/v3/start/upgrade.html#changes-to-redirect

路线示例(可行)

$app->get('/login/', function ($request, $response, $args) use($app) {
    return $response->withRedirect('/new-url');
});

中间件示例(有效)

$auth = function ($request, $response, $next) {
    if (!isset($_SESSION['Account'])) {
        return $response->withStatus(302)->withHeader('Location', '/new-url/');
    }
};

控制器示例(不起作用)

$app->get('/login/', function ($request, $response, $args) use($app) {
    return (new Login($app))->TestLoginRedirect();
});

 ....

class Login {

     protected $App;

    public function __construct($app){
          $this->App = $app;
    }

    public function TestLoginRedirect(){
       return $this->App->getContainer()->response->withRedirect('/new-url');
    }
}

其他重定向代码段尝试

return $this->App->getContainer()->response->withStatus(301)->withHeader('Location', '/new-url/');
return $this->App->redirect('/', '/new-url/');

1 个答案:

答案 0 :(得分:2)

在您的控制器示例中,路由回调必须返回响应对象,但不返回任何内容。它应该更改为:

$app->get('/login/', function ($request, $response, $args) use($app) {
    return (new Login($app))->TestLoginRedirect();
});