Search code examples
zend-frameworkhttp-redirectreroute

Zend - Conditionally reroute all pages


I'd like to be able to reroute or redirect all requests to my site to a specific page, if a conditional passes. I'm assuming this would have to be done somewhere in the bootstrap or with the dispatcher, but I'm not sure exactly what the best/cleanest way to go about it would be.

No .htaccess redirects since a condition needs to be tested for in PHP

Here's what I'd like:

if( $condition ) {
    // Redirect ALL Pages/Requests
}

// else, continue dispatch as normal...

The idea here is that we can setup the entire website and send everything to a splash page until a specified date/time, at which point it would 'auto launch' itself essentially.


Solution

  • Indeed, I'd go for a plugin.

    In library/My/Plugin/ConditionallyRedirect.php:

    class My_Plugin_ConditionallyRedirect extends Zend_Controller_Plugin_Abstract
    {
        public function routeStartup(Zend_Http_Request_Abstract $request)
        {
            // perform your conditional check
            if ($this->_someCondition()){
                 $front = Zend_Controller_Front::getInstance();
                 $response = $front->getResponse();
                 $response->setRedirect('/where/to/go');
            }
        }
    
        protected function _someCondition()
        {
            // return the result of your check
            return false; // for example
        }
    
    }
    

    Then register your plugin in application/configs/application.ini with:

    autoloaderNamespaces[]                        = "My_"
    resources.frontController.plugins.conditional = "My_Plugin_ConditionallyRedirect"
    

    Of course, other preferences/requirements for classname prefixing and for file location would entail slightly different steps for autoloading and invocation.