Zend Framework – Adding Custom Layouts for Each Module

There are several sources out there that explain how you can create a layout for each module, however, none that I have found did it quite right.

http://www.skyrocket.be/2009/01/11/admin-cms-routes-in-zend-framework/

The problem I have seen is that the layout will be registered and everything is all fine and dandy until you run into an exception and an error handler needs to be called. Then there are issues in finding the correct path for the layout etc…

Just do a search in google for ‘zend set default layout path module’ and you will see what I am talking about. The bug seems to keep getting pushed back in the framework, (http://framework.zend.com/issues/browse/ZF-4373)but I found an easy fix – hopefully I don’t eat my words later on!

The key is in which dispatch method you use in your plugin – I have seen preDispatch and dispatchLoopStartup being used (http://framework.zend.com/manual/en/zend.controller.plugins.html)

However in this case it needs to be postDispatch as my following plugin demonstrates:

class Plugin_Module extends Zend_Controller_Plugin_Abstract
{
    
	public function postDispatch(Zend_Controller_Request_Abstract $request)  
	{  
         // Set the layout directory for the loaded module 
        $front_controller = Zend_Controller_Front::getInstance();  
        $module_directory = $front_controller->getModuleDirectory();
		$layoutPath = $module_directory . '/views/layouts/';           
		Zend_Layout::getMvcInstance()->setLayoutPath($layoutPath)->setLayout('layout');  
   
        // Configure the error plugin to use the loaded module  
        // so we can use module-specific error handling  
        $errorPlugin = $front_controller->getPlugin('Zend_Controller_Plugin_ErrorHandler');  
        $errorPlugin->setErrorHandlerModule($request->getModuleName());  
	}
		
}
Thursday, September 17th, 2009 Zend Framework

1 Comment to Zend Framework – Adding Custom Layouts for Each Module

  • Mariusz says:

    Really nice tutorial mate! Keep it going, cheers

  • Leave a Reply

    You must be logged in to post a comment.

    [ad code=1 align=center]