Ever wondered how to create a nifty little Controller Plugin for Zend Framework that will build your navigation for you and automatically send it down to the view for use in your view and layout scripts? Well here is something you might find handy. It shows how to register your controller plugin, and a basic overview of what a navigation controller plugin might look like.

Please Note: This was written when the current version of Zend Framework was 1.10.2

Step 1: Application ini

In your application config

autoloaderNamespaces[] = "My_"

Step 2: Bootstrap

In your Bootstrap file

protected function _initRegisterControllerPlugins() {
	$this->bootstrap('frontController') ;
	$front = $this->getResource('frontController') ;
	$front->registerPlugin(new My_Controller_Plugin_Navigation());
}

Step 3: Controller Plugin

Now, create a new file called “Navigation.php” under your “/path/to/lib/My/Controller/Plugin/” directory. This will be our Controller Plugin.

<?php

	class My_Controller_Plugin_Navigation extends Zend_Controller_Plugin_Abstract {

		public function preDispatch(Zend_Controller_Request_Abstract $request) {
				// Get the view, we'll need to assign the navigation to it later
			$viewRenderer = Zend_Controller_Action_HelperBroker::getStaticHelper('viewRenderer');
			if (null === $viewRenderer->view) $viewRenderer->initView();
			$view = $viewRenderer->view;

				// Create a new Navigation Object
			$container = new Zend_Navigation();

				// Create the pages
			$pages = array(
				array(
					'label' => 'Home',
					'uri' => '/',
					'pages' => array(),
				),
				array(
					'label' => 'Page 2',
					'uri' => '/page-2',
					'pages' => array(),
				),
				array(
					'label' => 'Page 3',
					'uri' => '/page-3',
					'pages' => array(),
				),
			);

				// Set the pages to the navigation container
			$container->setPages($pages);

				// Set the active page
			$activePage = $container->findByUri($request->getRequestUri());
			$activePage->active = true;

				// Assign the navigation to the view
			$view->navigation($container);
		}

	}

?>

Step 4: Output the navigation

Now you can generate your top level navigation from within your view or layout.

<?php echo $this->navigation()->menu()->setMaxDepth(0); ?>

Hope you enjoyed this brief overview of how to create a Navigation helper. As you can see, if your structure is stored in a database table this would be really easy to modify to place it inside the Zend_Navigation object.

Published on Monday, 19 April 2010