Categories


Archives


Recent Posts


Categories


Controller _redirects are Not Immediate

astorm

Frustrated by Magento? Then you’ll love Commerce Bug, the must have debugging extension for anyone using Magento. Whether you’re just starting out or you’re a seasoned pro, Commerce Bug will save you and your team hours everyday. Grab a copy and start working with Magento instead of against it.

Updated for Magento 2! No Frills Magento Layout is the only Magento front end book you'll ever need. Get your copy today!

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.

Copyright © Alana Storm 1975 – 2023 All Rights Reserved

Originally Posted: 25th June 2011

email hidden; JavaScript is required