While working with Zend Framework, you must have asked yourself “Is there an easy way to redirect to another controller/action?”
Well, there is. When redirecting inside a controller, the first method we think about will probably be $this->_redirect(). This is quick, but it only accepts a URL. This means you have to create a URL to a specific route yourself. Either with the $this->view->url() URL view helper (which is not a pretty sight) or by assembling a route.
Yes, there is also $this->_forward() which sends your request to another controller/action, but it also goes through all init() logic again and forwarding isn’t suited for every situation (e.g. after a form POST).
But there is a far more flexible way: the less known Redirector action helper. Actually, $this->_redirect() uses it, but it provides easier ways to redirect to a specific route:
$redirector = $this->getHelper('Redirector');
$params = array(
'controller' => 'my-controller',
'action' => 'my-action',
'other-param' => 'value'
$redirector->gotoRoute($params, 'my-route', true);
Its usage will be self explanatory (actually the parameters are the same as the URL view helper), but I want to add a little note about the last parameter (which the URL view helper also accepts): if true, it “resets” your route, meaning all other parameters currently in your Request object are removed. This implies that when setting it to false (which is the default) parameters you have in your “current URL” will be reused (unless overwritten).
This can be particularly useful when passing search query, paging,… parameters from one page to another.
So, next time you need to redirect: pull out the Redirector action helper.
Tags: zend framework