我是否理解正确,$this->dispatcher->forward()或者$this->response->redirect()我需要手动确保其余代码不会被执行?如下,或者我错过了什么?
public function signinAction()
{
if ($this->isUserAuthenticated())
{
$this->response->redirect('/profile');
return;
}
// Stuff if he isn't authenticated…
}
Run Code Online (Sandbox Code Playgroud)
Ian*_*hek 27
在使用Phalcon超出其能力的核心项目工作近一年之后,我想澄清一些事情并回答我自己的问题.要了解如何正确地执行重定向和转发,您需要了解Dispatcher :: dispatch方法的工作原理.
看一下这里的代码,虽然它对我们大多数人来说都是C mumbo-jumbo,它的写得非常好并且有文档记录.简而言之,这就是它的作用:
_finished属性变为true或发现递归.true,因此当它开始下一次迭代时,它将自动中断._returnedValue财产(你猜怎么着!)返回的值.Dispatcher::forward方法,它将更新的_finished财产退还false,这将使该while循环从该名单中的第2步继续.因此,在进行重定向或转发之后,您需要确保只有当代码是预期逻辑的一部分时才会执行代码.换句话说,您不必返回return $this->response->redirect或的结果return $this->dispatcher->forward.
做最后一件事似乎很方便,但不是很正确,可能会导致问题.在99.9%的情况下,你的控制器不应该返回任何东西.例外情况是您实际知道自己在做什么,并希望通过返回响应对象来更改应用程序中呈现过程的行为.最重要的是,您的IDE可能会抱怨返回语句不一致.
要完成,从控制器内重定向的正确方法:
// Calling redirect only sets the 30X response status. You also should
// disable the view to prevent the unnecessary rendering.
$this->response->redirect('/profile');
$this->view->disable();
// If you are in the middle of something, you probably don't want
// the rest of the code running.
return;
Run Code Online (Sandbox Code Playgroud)
并转发:
$this->dispatcher->forward(['action' => 'profile']);
// Again, exit if you don't need the rest of the logic.
return;
Run Code Online (Sandbox Code Playgroud)
小智 10
你需要像这样使用它:
return $this->response->redirect('/profile');
Run Code Online (Sandbox Code Playgroud)
要么
return $this->dispatcher->forward(array(
'action' => 'profile'
))
Run Code Online (Sandbox Code Playgroud)