The Navigation Link View Helper
Tuesday, October 27, 2009

In this post we will look at a custom view helper, which is used on the sample website to render a link to a page in the site navigation.

The Zend_Navigation module allows us to build up a collection of objects that represent the pages on the site. These pages can then be rendered in different ways, such as a menu or a sitemap.

The helper covered in this post makes use of the Zend_Navigation object that was initialised in the bootstrapping process, as described in the post Bootstrapping the Application: the Standard Navigation Resource Plugin. Each page added to the navigation was given a unique ID. The helper takes this unique ID, along with some text for the link, and it uses the ID to retrieve the URL of the page from the navigation container object. This allows the exact URL of a page to be stored in just one place, so that it can be changed easily if necessary.

The helper is called Default_View_Helper_NavLink; the prefix Default_View_Helper was specified in the bootstrapping process, as described in the post Bootstrapping the Application: a Custom View Resource Plugin.

The helper class is stored in a file called NavLink.php, which is in the views/helpers directory.

Here is the code used to implement the class:

<?php
class Default_View_Helper_NavLink extends Zend_View_Helper_Abstract
{
  public function navLink($pageId, $label)
  {
    // Get navigation container
    $container = $this->view->navigation()->getContainer();
 
    // Get the page
    $page = $container->findOneBy('id', $pageId);
 
    // If the page is found, generate a link 
    // with the specified label text
    if (isset($page))
    {
      $html = sprintf('<a href="%s">%s</a>', $page->getHref(), $label);
    }
    // Otherwise just return the label text 
    else
    {
      $html = $label;
    }
 
    return $html;
  }
}

The class contains a method with a name corresponding to the basic helper name, which is essentially the class name but without the prefix. This corresponds to the name of the method used to invoke the helper from the view script.

Note that when a Zend_Navigation object has been set up via a resource plugin, it is automatically available from the view object via the call:

$this->view->navigation()

This object reference is used to retrieve the page container, which can then be searched for the relevant page. This is then used to generate the link.

Posted by James at 11:24 pm   1 comment

One Response to “The Navigation Link View Helper”

  1. Henry Hayes says:

    That’s quite a good solution. A more thorough navigation link view helper is included in the YinYang Zend Framework Supplement Library.

Leave a Reply