I’ve just finished watching some of the archived webinars related to Zend Framework over at Zend.com, and found some great information about rendering view output into a sitewide template in the MVC applications with Zend Framework webinar.
Since I’m currently developing a website with multiple modules, each having their own distinct look, I’d like to extend the examples provided in the webinar to allow specifying per-module templates. Here is what I came up with:
First, modify the example to add private member variables $_template and $_module and add a constructor that accepts and stores values for these variables.
class My_Plugin_RenderIntoTemplate extends Zend_Controller_Plugin_Abstract
{
private $_template = null;
private $_module = null;
public function __construct( $template, $module = 'default' )
{
$this->_template = $template;
$this->_module = $module;
}
Next, modify the dispatchLoopShutdown() method in the example to add a check that returns immediately if the current module is not the module specified at instantiation time.
public function dispatchLoopShutdown()
{
if( $this->_module != $this->getRequest()->module ) {
return;
}
$view = Zend_Controller_Action_HelperBroker::getStaticHelper('viewRenderer')->view;
if (empty($view)) {
return;
}
$response = $this->getResponse();
$content = $response->getBody();
$view->content = $content;
$response->setBody($view->render($this->_template));
}
}
Finally, register instances of the plugin with the front controller in the bootstrap code:
// Set up the Front controller.
require_once 'Zend/Controller/Front.php';
$front = Zend_Controller_Front::getInstance( );
$front->addModuleDirectory( '../application/modules' )
->registerPlugin( new My_Plugin_RenderIntoTemplate( 'foo-template.phtml', 'foo' ) )
->dispatch( );
In my example, I am using the conventional modular directory structure as outline here. In this case, the script named in the plugin constructor should be located at the application/modules/foo/views/scripts/foo-template.phtml.


