Skip to content

Zend Framework Modules and Layouts

December 22, 2009

I’m really getting into Zend now! I recently converted my test app into a module-based structure. Along with that came the desire to have a different layout for each module. Looks like I’m not the only one who has ever wanted to be able to do this. You’d think it would be something trivial, but that’s not the case. Here are the steps I took to get it working in a pretty clean way.

  1. I ended up removing all references to layout from the config file since I can’t figure out how to get access to them in the way that I needed.
  2. I created a front controller plug-in which initializes the layout based on the request’s module. It sets the layout and the layout path. See code below.
  3. I added an _init method to the default bootstrap file that loads the plug-in I created.

I saw somewhere that there is also a Zend_Layout_Controller_Plugin_Layout class that you can extend instead of the usual Zend_Controller_Plugin_Abstract. I wasn’t totally sure of what benefits the former had over the latter, so I stuck with the norm. There was also varying information as to which function to override in the plugin (preDispatch, dispatchLoopStartup, etc). I went with preDispatch and it works.

Here is my plug-in code:

class App_Controller_Plugin_Layout extends Zend_Controller_Plugin_Abstract
{
    public function preDispatch(Zend_Controller_Request_Abstract $request)
    {
        Zend_Layout::startMvc(array(
    	    'layout' => $request->getModuleName(),
    	    'layoutPath' => APPLICATION_PATH . '/modules/' . $request->getModuleName() . '/layouts/scripts'
        ));
    }
}

Here is the _init method that goes in your main bootstrap file:

protected function _initLayout()
{
    $frontController = Zend_Controller_Front::getInstance();
    $frontController->registerPlugin(new App_Controller_Plugin_Layout());
}

I’m not sure if there are any downsides to this method of getting different layouts based on the module. Make sure that your layout file has the same basename as your module. So, for instance, if you have the default module and an admin module then you’d end up with an admin layout located at application/modules/admin/layouts/scripts/admin.phtml.

Advertisement

From → Zend Framework

Leave a Comment

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.