RewriteRouter and Zend_Config play together

While getting the hang of the ZendControllerRewriteRouter, which is now included in Zend Framework 0.1.5, I was adding the routes in my index.php (bootstrap) file and wondered if there was any way of storing them elsewhere. It is possible to loop over ZendControllerRewriteRouter::addRoutes() but the method I will describe here is based on some recent updates to ZendControllerRewriteRouter by its author Michael Minicki.

The point of RewriteRouter is to map urls, like, to whatever controller, action and parameters needed without having to use external (and often painful!) methods like modrewrite.

For the sake of this article I'll use a relatively simple URL...

First setup some routes in a config file "routes.php". Note that this does require the latest version of the RewriteRouter which needs to be checked out from the subversion repository...

$config['routes']['articles'] = 
new Zend_Controller_Router_Route('articles/:category', 
array('category' => 'all', 
       'controller' => 'articles', 
       'action'      => 'index' ), 
       array('category' => '[a-z_]+') );

This establishes a route called "articles" that will respond to any url of the form "/articles/whatever" with the colon in :category indicating that it is an url variable that can be recovered through ZendControllerAction::_getParam( 'category' ). The controller and action indexes make the action "indexAction" in the controller file "ArticlesController.php" the final target. To cover cases where there is no category specified the default setting "all" is given. For extra assurance :category has to be a string containing only lower case letters and underscores as indicated by the final requirements array.

Next load them into the bootstrap file using ZendConfigArray:

$routes = new Zend_Config( 
       '../application/configuration/routes.php', 'routes' ) );

Then create the RewriteRouter object and pass it the $routes...

$router = new Zend_Controller_RewriteRouter;
$router->addRoutes( $routes );

All that is needed now is to pass the $router to the front controller...

$controller = Zend_Controller_Front::getInstance();
$controller->setRouter( $router );

That's it, now the routes are nicely stored outside of the bootstrap file and with the rest of the domain files.


I should also mention that it's well worth getting involved with the development of the framework even if you can only do so in a small way. After a relatively short discussion via the issue tracker about having some means to load routes in one hit, Michael Minicki had implemented one (thanks Michael).