Magento Version: 1.5.1
If you’ve spent anytime with the Magento core controllers, you’re probably aware you can kick off an HTTP redirect with something like
$this->_redirect('catalogsearch/term/popular/');
There’s two things about this you should be aware of. The _redirect
method does not automatically halt execution, and the last _redirect
in wins. If you want to redirect and then bail, use
$this->_redirect('catalogsearch/term/popular/');
return;
This will return immediately from the controller, ensuring no other redirects win.
By not exiting immediately, this allows the controller to indicate a redirect should occur, while still allowing any other system events and/or tasks that need to happen after a controller action is fired can happen.
This can be confusing to old time PHP developers, as header('Location: ...');
is usually immediate. If you take a look at the definition of _redirect
protected function _redirect($path, $arguments=array())
{
$this->getResponse()->setRedirect(Mage::getUrl($path, $arguments));
return $this;
}
You can see it’s marking the response object with a redirect. When Magento’s system code goes to output the response object, it notices the redirect, and issues that instead of HTML output.
The idea here is the controller should never, directly, cause the browser to redirect. That’s the responsibility of the Response object, and that’s why PHP keeps going after you call _redirect
.