How to redirect to a different controller action in Zend

Sonu Jha picture Sonu Jha · May 30, 2013 · Viewed 29.7k times · Source

I am creating a simple website where users can sign up, and then sign in and add text articles. Without signing in, a visitor will have the role of a guest, and will only be able to view articles. I am doing this as an exercise in Zend framework 1, as I have just begun learning Zend. I will make a controller AuthController for login, but I want to know how do I redirect to the login action in that controller, from my indexAction in IndexController. Also, how do I make use of a custom plugin to implement this kind of access control? How do I invoke it?

Answer

RockyFord picture RockyFord · May 30, 2013

jalpesh and Hasina are both correct with their short answers.

Jalpesh's example would be a shorthand call to the action helper redirector(), which defaults to the gotoSimple() method of redirection, except he seems to have the parameters backwards.

//corrected
$this->_helper->redirector($action, $controller);

would be more verbosely called as:

$this->getHelper('Redirector')->gotoSimple($action, $controller = null, $module = null, array $params = array());

There are several ways to use the Redirector action helper, this is just a very common example.

The example provided by Hasina is a call to the controller utility method _redirect() a much more limited bit of code then the Redirector helper is but still very useful.

//only accepts a url string as the first arg
//deprecated as of ZF 1.7 still in documentation
$this->_redirect($url, array $options = array());

apparently as of ZF 1.7 there is a new method not in the documentation (found this bit in the docblock) that is prefered:

//valid as of ZF 1.7, not in documentation
$this->redirect($url, array $options = array());

Both of these utility methods are proxies for:

 Zend_Controller_Action_Helper_Redirector::gotoUrl()

Hope this helps