Using Zend 1.x to Create a Plugin That Displays a Sidebar if it Exists

A lot of sites like to use sidebars on their pages so with Zend and MVC I like to have the following setup with sidebars: (i put a sidebar.phtml under each pages view scripts folder.)

Since all of my pages will not use a sidebar, I tell my layout to only include it if there is a side bar:


layout()->content; ?>

sidebar)): // Only show the sidebar if there is one. ?>


Now I need to set $this->sidebar to something. One way to do this is to go to every controller and set it in the init function:

public function init()
$this->view->sidebar = $this->render('sidebar.phtml');

But why do that when you could just do it once as a plugin. The first step is to create the Sidebar plugin:


// Get an instance of the view and set it's path to the view/scripts directory.
$view = Zend_Controller_Action_HelperBroker::getStaticHelper('Layout')->getView();

// Try to render the sidebar.
try {
$view->sidebar = $view->render($controller . "/sidebar.phtml");
// Since not all pages will have a sidebar, just ignore any exceptions caused by rendering non existing files.
catch(Exception $e){

This plugin looks for a sidebar.phtml file in the controllers view scripts directory, and if it finds it, it will set the views sidebar variable, if not, it will catch the exception and move on.

Once you’ve created the plugin, you just need to setup your application to user it by first updating you application.ini file:

autoloaderNamespaces[] = "Stricks_"

Then register the plugin in your Bootstrap.php

protected function _initPlugins()
$bootstrap = $this->getApplication();
if ($bootstrap instanceof Zend_Application) {
$bootstrap = $this;
$front = $bootstrap->getResource('FrontController');

$front->registerPlugin(new Stricks_Controller_Plugin_Sidebar());


Leave a Reply

Your email address will not be published. Required fields are marked *