May 27th, 2011 · php zend framework 1

Nested controllers in Zend Framework!

Did you know that action controllers in Zend Framework can be nested (ie: placed in sub-directories within the controllers directory)? Neither did I! This undocumented feature was pointed out to me during a recent conversation with Ryan Mauger (bittarman) and Matthew Weier O'Phinney (weierophinney) on the #zftalk.dev IRC channel. Needless to say, this made my day!

However, they also pointed out that the default router does not handle routing to these nested controllers in a "pretty" fashion. For example, a nested controller Admin_Page_SubPageController (modules/admin/controllers/Page/SubPageController.php) would be accessed via the URI admin/page_sub-page/:action. This could be avoided by creating a custom route for each nested controller, and Ryan kindly provided an example in which he hand-coded a route for each nested controller in a bootstrap method. This approach, however, will add a lot of bulk to the bootstrap if you have many nested controllers. The solution: automate it!

I took Ryan's example, mixed in Matthew's backported ZF2 classmap-based autoloader, and created a bootstrap resource plugin which uses classmaps to automatically generate the necessary routes for you. I've posted the result, along with a sample application showing how to use it, on github:

https://github.com/adamlundrigan/zf1-nestedcontrollers