Zend Module Layout/Error Plugin

When working with modules in Zend Framework. You might want to separate out your admin’s layout from your user’s front end layout. And you might also want to have different error handling screens for those as well.

With the help of Daniel Cousineau’s Blog Post I was able to come up with the following Layout Plugin.

 


/**
 * Module Layout Plugin
 *
 * @author     Sean Thayne <sean@skyseek.com> http://www.skyseek.com
 * @author     Daniel Cousineau <dcousineau@gmail.com> http://www.toosweettobesour.com/ 
 */
class App_Layout_Plugin extends Zend_Layout_Controller_Plugin_Layout 
{
	public function preDispatch(Zend_Controller_Request_Abstract $request) 
	{
		$this->_setLayoutPath($request);
		$this->_setErrorController($request);
	}

	protected function _setLayoutPath(Zend_Controller_Request_Abstract $request)
	{
		$layoutPath  = APPLICATION_PATH;
		$layoutPath .= DIRECTORY_SEPARATOR . "modules";
		$layoutPath .= DIRECTORY_SEPARATOR . $request->getModuleName();
		$layoutPath .= DIRECTORY_SEPARATOR . "layouts";
		$layoutPath .= DIRECTORY_SEPARATOR . "scripts";

		Zend_Layout::getMvcInstance()->setLayoutPath($layoutPath);
	}

	protected function _setErrorController(Zend_Controller_Request_Abstract $request)
	{
		$front = Zend_Controller_Front::getInstance();

		//If the ErrorHandler plugin is not registered, bail out
		if( !($front->getPlugin('Zend_Controller_Plugin_ErrorHandler') instanceOf Zend_Controller_Plugin_ErrorHandler) )
			return;

		$error = $front->getPlugin('Zend_Controller_Plugin_ErrorHandler');

		//Generate a test request to use to determine if the error controller in our module exists
		$testRequest = new Zend_Controller_Request_HTTP();
		$testRequest->setModuleName($request->getModuleName())
					->setControllerName($error->getErrorHandlerController())
					->setActionName($error->getErrorHandlerAction());
					
		//Does the controller even exist?  
		if( $front->getDispatcher()->isDispatchable($testRequest) )
		{
			$error->setErrorHandlerModule($request->getModuleName());
		}
	}
}

You use the plugin pretty simply by modifying your Bootstrap to include a _initLayout method like so.

class Bootstrap extends Zend_Application_Bootstrap_Bootstrap {

	protected function _initLayout() {
		Zend_Layout::startMvc(array(
			'pluginClass' => 'App_Layout_Plugin'
		));
	}

}
Advertisements

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 )

Google+ photo

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

Connecting to %s