Archive for the ‘Zend’ Category.

Layouts Per Module In Zend

After the introductory Zend Quickstart Tutorial, one common initial request is to add support for modules which then quickly morphs into the need for per module layouts.

Views From the Hill has an excellent tutorial to do exactly that. Building upon these two resources with further improvement your directory structure might look like this:

/application
/config
/layouts
/scripts
/models
/modules
/default
/controllers
/views
/admin
/controllers
/layouts
/scripts
/views
/stats
/controllers
/views

The goal is to load a module specific layout only if it is available and revert to the default global layout in all other cases.

In our case only the admin module will have its own layout. To accomplish this we need to make some changes to the bootstrap.

Add the following to your bootstrap:


// Setup Module Path
define('MODULES_PATH', APPLICATION_PATH.'/modules');


You might prefer to define the modules path in a config file and store the information in the Zend_Registry. But for the purposes of brevity we will use a simple define statement here.

Next we setup the front controller and layout systems:


// Setup Front Controller

$frontController = Zend_Controller_Front::getInstance();
$frontController->addModuleDirectory(MODULES_PATH);
$frontController->setParam('env', APPLICATION_ENVIRONMENT);

// Setup Layout

Zend_Layout::startMvc(array(
'layoutPath' => APPLICATION_PATH . '/layouts/scripts',
'pluginClass' => 'Custom_Layout_Plugin'

));


Finally we add our Layout Plugin class:


/**
* Layout Plugin to enable per module layout scripts
*/

class Custom_Layout_Plugin extends
Zend_Layout_Controller_Plugin_Layout
{

public function
preDispatch(
Zend_Controller_Request_Abstract $request)
{

$module_name = $request->getModuleName();
$layout_path = MODULES_PATH . "/{$module_name}/layouts/scripts";

// Check if layout directory exists
if ( is_dir($layout_path) )
{
$this->getLayout()->setLayoutPath($layout_path);
}

}

}


And we are done!

When ever a module has a /modules/module_name/layouts/scripts directory the system will look for layout files there, otherwise it reverts to the global application/layouts/scripts.

We can delete the layout folder inside a module directory and the system will move to the default layout with no further configuration and vice versa.