Reputation: 105
Is is possible to redirect the user to a new URL from within a controller plugin, without having to return a response object to the controller?
Specifically I want to redirect the user to the secure version of the current URL. So in ZF2 I have this:
$url = 'https://'.$this->getURL();
$response = $this->getController()->redirect()->toUrl( $url );
return $response;
However in the Zend Framework 1 I was able to do:
$redirector = Zend_Controller_Action_HelperBroker::getStaticHelper('redirector');
$url = 'https://'.$this->getURL();
$redirector->gotoUrlAndExit($url);
Is it possible to essentially 'redirect then exit' in ZF2?
Upvotes: 1
Views: 10435
Reputation: 101
Inside your plugin just return the action:
return $this->getController()->getAction();
Upvotes: 0
Reputation: 1236
Assuming you are extending Zend\Mvc\Controller\Plugin\AbstractPlugin then you should be able to redirect like this:
$this->getController()->plugin('redirect')->toUrl($url);
return FALSE;
If you look at the toUrl method in Zend\Mvc\Controller\Plugin\Redirect, it looks like this:
/**
* Redirect to the given URL
*
* @param string $url
* @return Response
*/
public function toUrl($url)
{
$response = $this->getResponse();
$response->getHeaders()->addHeaderLine('Location', $url);
$response->setStatusCode(302);
return $response;
}
So obviously it is returning the response object, but it has also already added the header to it, and from the controller you don't have to explicitly return the response, so from your plugin you shouldn't either. I think it's commonly done, to maintain a fluent interface, but since you know you don't need it for anything else, you don't need to pass it back.
Note: I have not tested this from within a plugin, but I do this from within the controller and it works fine:
$this->plugin('redirect')->toUrl($url);
return FALSE;
Upvotes: 4