Robert Basic's blog

Chaining routes in Zend Framework

by Robert Basic on November 27, 2009.
Heads-up! You're reading an old post and the information in it is quite probably outdated.

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
public function _initRoutes()
    $this->_frontController = $this->getResource('FrontController');
    $router = $this->_frontController->getRouter();

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

    $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!

Tags: example, framework, php, route, routing, zend, zf.
Categories: Development, Programming.

Thanks for reading! If you require help on a PHP project of any kind, let's talk!

To get notified when I write a new blog post or make a new screencast, subscribe:

Recent posts