Multiple Paths for Zend_Layout (Modules Based Layouts)

There was some chatter about using module based layouts with Zend_Layout on freenode, so I thought I’d explore the idea a bit more.  There was this particular idea to use a plugin and a bit of application.ini/xml settings to configure it all.  But I’m a bit old school with my Zend Framework apps.

All of my sites have an action controller class (Site_Controller_Action which extends Zend_Controller_Action) which all of the individual controllers in all modules extend. (ie: IndexController extends Site_Controller_Action, and OtherModule_SillyController extends it also.)  This gives me a central point of being able to do fun things with my code.

One of these things is to enable per-module based layouts, with a fall back to the global layouts directory.  And as it turns out, it’s simple.  In my Site_Controller_Action::init() I have a short little block of code that looks like this:

php">
// add module based layout paths
$layouts   = "views/layouts/";
$moduleDir = Zend_Controller_Front::getInstance()->getModuleDirectory();
$this->layout->getView()->addScriptPath($moduleDir . DIRECTORY_SEPARATOR .$layoutPath);

And voila, now my modules can have their own little layout path if they want ‘em. They’ll automagically fall back to the global layout directory and everything else is the same as always. The only downside to this is it won’t work if you don’t have your action controllers setup the way I do. Essentially since Zend_Layout doesn’t support adding multiple paths, the work around is to grab the view and use it’s add path. Which is effectively what Zend_Layout does by itself just before it renders.

You can leave a response, or trackback from your own site.

Leave a Reply

Subscribe to RSS Feed Follow me on Twitter!