Reputation: 9076
I have been using ZF2 for a few months now and I am confused about how the controller redirect is supposed to work. Is it supposed to immediately stop processing the current action, and send the redirect request? Or is it supposed to complete processing of the current action, then perform the redirect?
Pretty fundamental question, huh?
Back in ZF1, I am pretty sure the redirection took place immediately (unlike forward()
, which was stored up until the current action was completed). I assumed it was the same case in ZF2 and so far that has been my experience, however today suddenly I find that controllers are storing the redirect up, and sending it at the end of the current action.
Here's an example:
public function testAction()
{
$this->redirect()->toUrl('/info');
echo 'Hello';
die();
}
In this case, the action will echo 'Hello' and then die.
I think that this is probably the normal course of events and that I have just (by sheer fluke) not noticed it before today. I just want to be sure though, before I go back and alter all my controllers. (The alternative explanation is that somewhere in my config I am destroying/overriding the redirect plugin).
Upvotes: 3
Views: 267
Reputation: 25431
In Zend Framework 2.*, execution is never halted (except for a particular upload progress handler and some locations in the console component).
Therefore, you have to stop your controller from dispatching manually:
public function testAction()
{
return $this->redirect()->toUrl('/info');
echo 'Hello'; // will never be executed
}
To be more precise, as of this callback (used when triggering a Zend\Mvc\MvcEvent::EVENT_DISPATCH
), any listener to the dispatch
event of an application that returns a ResponseInterface
causes a "short-circuit" to the application finish
event.
Short-circuiting (in the Zend\Mvc\Application
) basically causes subsequent events to be skipped and forces the application to directly trigger the Zend\Mvc\MvcEvent::EVENT_FINISH
event, therefore echoing the response (happens in a listener of the finish
event).
In this particular controller action, the call to the $this->redirect()->toUrl('...')
helper produces a Zend\Http\Response
, and since we directly return it, the short-circuit is triggered.
Upvotes: 6