views:

490

answers:

5

I need to redirect according to some conditions in the bootstrap file.
It is done AFTER the front controller and routes are defined.
How do I do that?
(I know I can simply use header('Location: ....) The point is I need to use the Router to build the URL.

A: 

The best way is probably a Controller Plugin

You can add a routeShutdown() hook that is called after routing has occured, but before the action method your controller is called. In this plugin you can then check the request data or maybe look for permissions in an ACL, or just redirect at random if that's what you want!

The choice is yours!

EDIT: Rereading your question, it looks like you're not even interested in the route - use routeStartup() as the earliest point after bootstrapping to inject your code.

David Caunt
A: 

I would grab the router from the front controller and call its assemble() method and then use header() :)

Regards,

Rob...

Rob Allen
I actually tried that before posting. Didn't work for some reason (there where no values). Do I have to init something in the router before using the assemble method? (thanks)
Itay Moav
Got a simple code sample?
Rob Allen
A: 

You can check the condition on "routeShutdown" method in plugin and then use $this->actionController->_helper->redirector() to redirect ;)

Tomáš Fejfar
+1  A: 

Hi guy, more than year later, i'm programming in ZF and I got this solution for your problem. Here is my function in bootstrap that determines where the user is logged on.

class Bootstrap extends Zend_Application_Bootstrap_Bootstrap

{

protected $_front;

(...)

protected function _initViewController() 
{
    (...)

    $this->bootstrap('FrontController');
    $this->_front = $this->getResource('FrontController');

    (...)
}

protected function _initLogado()
{
    $router = $this->_front->getRouter();
    $req = new Zend_Controller_Request_Http();
    $router->route($req);
    $module = $req->getModuleName();

    $auth = Zend_Auth::getInstance();
    if ($auth->hasIdentity()) {
        $this->_view->logado = (array) $auth->getIdentity();
    } else {
        $this->_view->logado = NULL;
        if ($module == 'admin') {
            $response = new Zend_Controller_Response_Http();
            $response->setRedirect('/');
            $this->_front->setResponse($response);
        }
    }
}

}

+1  A: 

Redirection should really not be in the bootstrap file... That will be one horrible night of debugging for the coder that ends up stuck with your code in a few years.

Use either a Front Controller Plugin, Action Controller Plugin, or do it in your Action Controller. Ultimately such a redirect should be avoided altogether...

balupton
Why the down vote?
balupton