Passing arrays to Zend_Controller_Router

PHP Web development Zend Framework June 23rd, 2008 by Eran Galperin

WARNING: The following contains unsanctioned HACKS to the Zend Framework. Use at your own discretion.

A big advantage to using the front controller in the Zend Framework is the ability to create nicely formatted urls. Instead of an ugly GET string we can pass parameters as slash delimited key -> value pairs. For example:
www.techfounder.com/index.php?post=passing_arrays&comment=3 can be replaced with www.techfounder.com/post/passing_arrays/comment/3
(On techfounder this is actually performed via mod_rewrite rules, but the principle is the same).

The implementation of the default router in the Zend Framework (Zend_Controller_Router_Rewrite) does not allow for passing arrays in this manner though, since previously set keys get overwritten if they are declared more than once. This is somewhere between semi-annoying to very annoying, so lets get straight to hacking it into submission.

Following the internals of the routing process we find the actual parsing of the URL address inside Zend_Controller_Router_Route_Module. Line 174 is where the assignment takes place:

  1. $params[$key] = $val; //Overwrites previously set value...

Which we modify to allow passing array variables by redeclaring same key names with different values:

  1. $params[$key] = (isset($params[$key]) ? (array_merge((array) $params[$key],array($val))): $val);

This short ternary statement casts the value into an array if its key was previously declared and merges it with the next value. Using this we can pass array variables in a nicely formatted URL address. For example, passing multiple posts id's:
www.techfounder.com/show/posts/5/posts/8/posts/40

I tried to create an extension of Zend_Controller_Route_Module which performs this without modifying the core library files, however to work this class would also have to implement the Zend_Controller_Router_Route_Interface interface which means declaring 6 abtract methods... way too much for simply modifying one line of code. If anyone has a better suggestion on how to accomplish what I proposed here, I am open to suggestions.

Tags: ,

Enter your email address to receive notification about new posts.

If you liked this article you should follow me on Twitter and/or share below: