Chaining routes in Zend Framework

on November 27, 2009. in Development, Programming. A 2 minute read.

On a forum, there was a question today, about adding language “support” to the routes using Zend Framework. The guy wanted routes like /en/foo/bar or /de/baz. I wrote there an example for that using Zend_Router_Routes_Chain, so just posting that example here, too :)

For what chains are for, is described in the manual, so I won’t be covering that :P

Basically, we’re prepending the language route to the other routes. This way, we have defined the route for the languages in one place only, plus, the other routes don’t have to worry about the language, too.

// this goes in the bootstrap class
<?php
public function _initRoutes()
{
    $this->bootstrap('FrontController');
    $this->_frontController = $this->getResource('FrontController');
    $router = $this->_frontController->getRouter();

    $langRoute = new Zend_Controller_Router_Route(
        ':lang/',
        array(
            'lang' => 'en'
        )
    );
    $contactRoute = new Zend_Controller_Router_Route_Static(
        'contact',
        array('controller'=>'index', 'action'=>'contact')
    );
    $defaultRoute = new Zend_Controller_Router_Route(
        ':controller/:action',
        array(
            'module'=>'default',
            'controller'=>'index',
            'action'=>'index'
        )
    );

    $contactRoute = $langRoute->chain($contactRoute);
    $defaultRoute = $langRoute->chain($defaultRoute);

    $router->addRoute('langRoute', $langRoute);
    $router->addRoute('defaultRoute', $defaultRoute);
    $router->addRoute('contactRoute', $contactRoute);
}

Assuming that we have an Index controller, with actions index and contact and a Foo controller with actions index and bar, paired with the routes from the above example, we could do requests like:

/ => /index/index/lang/en
/de => /index/index/lang/de
/sr/contact => /index/contact/lang/sr
/en/foo => /foo/index/lang/en
/fr/foo/bar => /foo/bar/lang/fr

Requesting a page like, e.g. /de/baz, would give us a 404 page, cause we don’t have a Baz controller.

HTH :)

Happy hacking!