Navigation, Breadcrumbs, & Sitemap with Zend Framework

Let Zend Framework do all the work when it comes to your Navigation, and stop hard coding stuff in either layouts or view files!

First up, in the configs folder, create an XML file called navigation.xml :

<?xml version="1.0" encoding="UTF-8"?>
       <label>About Us</label>
       <label>Contact Us</label>
       <label>Site Map</label>
       <label>Privacy Policy</label>
       <label>Terms of Use</label>

Stick this _init method into your bootstrap :

protected function _initNavigation()
 $layout = $this->getResource('layout');
 $view = $layout->getView();
 $config = new Zend_Config_Xml(APPLICATION_PATH.'/configs/navigation.xml','nav');
 $nav = new Zend_Navigation($config);

This loads the XML into a Zend Config, which gets passed to Zend_Navigate, and finally to the view. To get this stuff displaying on your pages, go into your layout.phtml and add this:

echo $this->navigation()->menu();

For breadcrumbs, put this into your Controllers _init method. This figures out where in the XML tree we are:

$uri = $this->getRequest()->getPathInfo();
if (($activeNav = $this->view->navigation()->findByHref($uri)) !== null) 
 $activeNav->active = true;
else if (($activeNav = $this->view->navigation()->findByUri($uri)) !== null) 
 $activeNav->active = true;

And back in the layout, add this:

echo $this->navigation()->breadcrumbs()->setMinDepth(0)->setLinkLast(false)->setSeparator(' | ');

The setLinkLast false makes the last breadcrumb non linkable (I mean we’re on that page!), and setSeparator can contain any HTML.

Finally, to get a sitemap that Google can accept, in your sitemap’s controller action, we only need to add this :

 echo $this->view->navigation()->sitemap();

And thats us! Nice n easy! Bonus brownie points for anyone who posts a reply showing how to separate footer links from the nav!


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s