Zend Framework: Encapsulating routes into modules

You can encapsulate routes into modules by splitting the routes into different files and extending the Zend_Controller_Router_Rewrite class. But, what if you want to use the Redirector helper to set a URL based on a registered route?

Brenton Alker wrote:

A problem I have encountered is that because only the routes matching the first section of the URL are loaded, reversing routes to generate URLs for other sections doesn’t seem possible. You can’t generate a URL for something in “gallery” from within the blog because the gallery routes don’t exist.

You have to load the routes first before generating the URL. If you open the Zend_Controller_Action_Helper_Redirector class, you’ll see that the setGotoRoute() method gets an instance of the Router and retrieves the route based on a given name:

$router = Zend_Controller_Front::getInstance()->getRouter();
$route = $router->getRoute($name);

So, the only thing you need to do is overwrite the getRoute() method in your custom Router class and load the corresponding file. For example:

public function getRoute($name)
{
    if (!isset($this->_routes[$name])) {
        // load file or throw exception
    }
    return $this->_routes[$name];
}

That’s it. The same applies to Zend_Controller_Action_Helper_Url (there’s an example here).

About these ads

2 thoughts on “Zend Framework: Encapsulating routes into modules

  1. Martel and Ben have introduced route chaining into trunk, and this will be the solution used for hostname based routing for 1.6. For 1.7, they plan to modify the routes to allow partial matching, which will allow you to chain several routes together to get a match. One primary use case is for localized routes, where all routes need a language string — this would require a single route which then chains a variety of other routes. This should result in better routing performance, as well as more flexible and extendible routing solutions.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s