Benjamin Tigano Developer at Large

Adding site navigation

When I first started exploring the Zend Framework (ZF), one of the issues I ran into was generating menu's. My solution (in an effort to not go too much deeper into what ZF had to offer while I focused on the basics) was to put some code in the layout file where I wanted the menu. The menu was an array of titles and URL's that I'd loop through and display. I wanted to add a CSS class to the menu item if that's where the user was, so I checked the controller and action off of the request to see if it matched the URL, and if it did, I added the CSS. It was simple and quick, but it was messy.

I recently discovered a component in ZF for solving this problem - Zend_Navigation. The best part about this component is that you can build the menu via code, or from an XML file. I've been testing out both, but I find the XML file to be much easier and clean-cut. Rather than putting the code into the layout again, I created a a view helper in /application/views/helpers named MenuHelper. Below is the view helper class

<!--?php class Zend_View_Helper_MenuHelper {    public $view;    public function menuHelper() {       $config = new Zend_Config_Xml(APPLICATION_PATH.'/configs/menu.xml', 'nav');       $container = new Zend_Navigation($config);       $this--->view->navigation($container)->UlClass = "main-nav";
      return $this->view->navigation()->menu()->render();

   public function setView(Zend_View_Interface $view) {
      $this->view = $view;

The lines specific to building the menu are highlighted. We start by reading in our configuration file, and defining the section we want to load - "nav". We then create the Zend_Navigation object, define a class for the ul element ("main-nav"), and then render the menu to the view.

In our layout, we call the menu helper just like any other view helper:

<!--?php echo $this--->menuHelper(); ?>

Almost done. Next, we need to populate the XML file with the menu items. In my example, I added a link back to, and a link to the homepage of my site (index/index.) Even though it's listed second, the home link will appear first because the order value is less than the order value on the zend link. The file is stored in the application/configs directory, named "menu.xml".

<!--?xml version="1.0" encoding="UTF-8"?-->





Lastly, we want to make sure that we apply a specific CSS class to the menu item if that's our current URL. To do that, we do nothing! Why? Because Zend_Navigation does that for us!

Want to read more about what Zend_Navigation has to offer? Check out the reference guide on Zend's website here.

As usual, if you have any questions, please leave them in the comments.

Download the project

Next up, using alternate layouts.

Fork me on GitHub