Zend Framework: Redirect – The Easy Way
Posted on October 28th, 2008 in PHP, Web Development, Zend Framework | 8 Comments »
It is common to need to redirect from one controller action to another or even from one controller to another when coding with the Zend Framework. From my code reviews, I find that many people are using the _redirect() method from Zend_Controller_Action. This function takes a url and an optional array of options. This is a fine choice if you need to redirect to a completely different website but the vast majority of redirect in a web application is to another action within the same application.
The lesser known, and much easier, way to redirect within the Zend Framework is to use the Redirector Zend Controller Action Helper
The syntax is much easier since you don’t have to reconstruct a complete url, you just pass in the action and controller names. In fact, the only required parameter is the name of the action. If only an action name is given then the current controller is assumed to be the target controller. Here is a quick example.
_helper->redirector('target', 'example');
// NOTE: 'example' is optional since the default target controller
// is the current controller
}
public function targetAction() {
// Do some things...
}
}
?>
8 Responses
Is this the same as $this->_forward() in Zend_Controller_Action?
Zachary, when you use $this->_forward() you transfer the execution of the current request to a different action. When you use the Redirector helper you actually make another round trip from the server to the client. So, if you use _forward() the url on the browser doesn’t change. If you redirect, the url in the browser will change. Therefore, using _forward() will be a less resource intensive call, but sometimes you may actually need to redirect to a new location in your app, such as an access denied situation.
Oops, hasty response leads to typo. I meant this->_redirect().
Ok, forget everything I’ve said. I read the post again and I’m a dummy.
Thanx i was looking exactly this!
Thank you very much!
i could not got, that the first is action, and second is controller…
Was really wondering what is a problem;)
But your note:
# / NOTE: ‘example’ is optional since the default target controller
# // is the current controller
makes thing understandable;)
Can I call other action with parameters using this helper? How?
Thanks man!
But you’re a bit wrong. You said:
“_helper->redirector(‘target’, ‘example’);”
Actually it is:
“$this->_helper->redirector(‘target’, ‘example’);”
Or were you supposed to just grasp that like everything else in the ZF world..?