Search code examples
phpzend-frameworkzend-controller

Implementing vanity urls (like http://facebook.com/JohnDoe) in Zend framework?


Is there anyway to create a vanity url "catch all" route whilst maintaining the default /module/controller/action/value routing structure?

Thanks!


Solution

  • You could use the PreDispatch() hook on a front controller plugin. Like so:

    In your bootstrap

    <?php
    ...
    $frontController = Zend_Controller_Front::getInstance();
    // Set our Front Controller Plugin
    $frontController->registerPlugin(new Mystuff_Frontplugin());
    
    ?>
    

    Then inside Mystuff/Frontplugin.php

    <?php
    
    class Mystuff_Frontplugin extends Zend_Controller_Plugin_Abstract
    {
        ....
    
        public function preDispatch(Zend_Controller_Request_Abstract $request)
        {
            ....
    
            $controllerFile = $this->_GetRequestedControllerFile();
    
            if (!is_file($controllerFile)) {
                // Controller does not exist
                // re-route to another location
                $request->setModuleName('customHandler');
                $request->setControllerName('index'); 
                $request->setActionName('index');
    
            }
        }
    
        ....
    }
    

    Also preDispatch() is a handy location to handle application wide authentication.