Posts Tagged ‘router’

Extending Zend URL

July 8, 2008

My friend Matt Turland ( and I have each been discovering the Zend Framework for seperate projects. Matt had a bit of a headstart on me, and when I started working, he offered me a plugin class he had written, View_Helper_Route. Zend Framework’s url helper tends to be a bit finicky, and route lets you enter url’s that make a bit more sense.

ex:  $this->url(array(“controller”=> “profile”,”action” => “index”,”id” => “5”), “default”, true);

or $this->route(“index”,”profile”,array(“id”=>”12”));

Granted, at first glance neither one looks too clean. But route() can make assumptions that url() can’t. Each parameter passed in route goes through a check, (“if param is null, $request->getParamName). So if we are jumping around in the same controller, route() turns into

This allows us to create relative links, instead of having to hard-code each link up to the module level. I ran into a bit of a fix using it today though, which is why I am writing this.

The URL method has an option parameter for which route to use, passed in after the array of controller information. Most of the time, you can pass it null and it will continue routing according to the last rule it used. If you have a site-wide rewrite, this makes sense. But for specific page rules, it can be a pain. My site doesn’t need a sitewide cleanup, we only want to not write each parameter into the url bar on pages with several get variables. no big deal, right? A page like profile/index/id/12/method/add/ becomes profile/12/add. The only problem is, for every url on that page or in the site’s navigation, $url throws an error without explicitly passing the optional parameter. The error is additionally tough to read:
Fatal error: Uncaught exception ‘Zend_Controller_Router_Exception’ with message ‘id is not specified’ in /domain/library/Zend/Controller/Router/Route.php:235

There are two neat solutions I’ve implemented in a patch to View_Help_Route. The first is simply to add another optional parameter that tells the router that if no route is specified, use default.  If we need a route, we can add one.
Additionally we can use the beautiful PHP magic method hasParam() to find out if this page is supposed to have a special router, and based on that, use it.
So now, any time I link to a profile, my router will always know to use the default, site standard route, or my profile route depending on the controller.
I’ve included my route injection from my bootstrap, as well as the class itself below.

If you decide to use the route class,  I recommend placing it in a library directory named after your app.
Also, make sure to replace [YourApp] in the code with the name of that directory.
Router Injection

View Helper Route