views:

76

answers:

3

Is there any real difference between

$this->_redirect('controller/action');

and

$request->setControllerName('controller')
        ->setActionName('action');

My guess is that the first one maybe uses the second one behind the scenes. Does anyone know?

+2  A: 

The first one is a physical redirect by sending 302 headers. The second one is more similar to what _forward() does - change the controller name and action for the current request.

Eran Galperin
+2  A: 

The difference is that the Redirector helper just sends HTTP redirection headers, while changing the request params requires the dispatcher to be run (once again if already ran) to make a successful redirection, so it is important where do you call the method.

Seems that the biggest difference is that the first one makes at least two HTTP requests (one to find the redirection, second to execute it), the other, just one when called before dispatch process (correct me if I am wrong).

takeshin
+4  A: 

The Redirector helper allows you to use a redirector object to fulfill your application's needs for redirecting to a new URL. It provides numerous benefits over the _redirect() method, such as being able to preconfigure sitewide behavior into the redirector object or using the built in gotoSimple($action, $controller, $module, $params) interface similar to that of Zend_Controller_Action::_forward().

The main differece compared to setController() and setAction() in the request object is that you'll change the url (302 redirection), not just the action. Also, as you can see, the _redirect() method is a shortcut to the redirecotor helper which provide more functionalities than just redirect. You can see those here: http://framework.zend.com/manual/en/zend.controller.actionhelpers.html#Redirector

The $this->_forward() method do the same as setController() and setAction() and is a method of Zend_Controller_Action class:

final protected function _forward($action, $controller = null, $module = null, array $params = null)
{
    $request = $this->getRequest();

    if (null !== $params) {
        $request->setParams($params);
    }

    if (null !== $controller) {
        $request->setControllerName($controller);

        // Module should only be reset if controller has been specified
        if (null !== $module) {
            $request->setModuleName($module);
        }
    }

    $request->setActionName($action)
            ->setDispatched(false);
}

If you're on Zend_Controller_Action you can use this method above, but if you're on Zend_Controller_Plugin for example you need to use the request object directly.

When you submit a form for example, it's a good pratice redirect instead of forward to prevent the form from being submitted twice if the user refresh the page.

For more information about this proccess:

http://framework.zend.com/manual/en/zend.controller.dispatcher.html

http://devzone.zend.com/article/11978

Keyne