Goals of the View Helpers

zend-frameworkThe View Helpers are useful classes in PHP for our views. This classes help us to remove repetitive statements in views because the methods can be packaged in that class and then, used across application. In this example I build a class to make custom list items with Bootstrap format.

 

Keys of View Helpers

  • Are classes
  • Extend of Zend_View_Helper_Abstract.

 

View Helper structure and example

Is very important to create right file structure.

File path: APPLICATION_PATH . 'views/helpers/Lists.php'

You don't need understand $page param, but it's a Zend_Navigation structure.

<?php
/**
 * This class makes links and menus with icons for the elements
 * in Bootstrap format
 *
 * @author Diego Nieto Muñoz
 */
final class Layout_View_Helper_Lists extends Zend_View_Helper_Abstract {
    
    public function lists() {
        return $this;        
    }
    
    /*
     * @page => Page of container from Zend_Navigation
     * 
     * Returns:
     * "<li><a href='LINK... ><i class='ICON'>NAME</i></a>" 
     */
    public function makeLink($page) {
        return '<li><a href="' . $page->controller . '/' . 
                $page->action . '"><i class="icon-' .
                $page->icon . ' icon"></i> ' . $page->label . '</a></li>';
    }
    
    /*
     * @link => Result of makeLink function
     * 
     * Returns <li> . LINK </li>
     */
    public function addLi($text) {
        return '<li>' . $text . '</li>';        
    }
    
    /*
     * @title => Item title
     * @icon => Name of Bootstrap icon, i.e. "icon-plus"
     * 
     * Returns:
     * <i class='ICON'>NAME
     */
    public function makeItem($title, $icon) {
        return '<i class="icon-' . $icon . ' icon"></i> ' . $title;
    }
    
}
?>

 

 

Also, is necessarily add the next line in your Bootstrap file:

 

<?php
class Bootstrap extends Zend_Application_Bootstrap_Bootstrap {
    ...
    protected function _initViewHelper() {
        $view->addHelperPath(APPLICATION_PATH . 
                    '/views/helpers', 'Layout_View_Helper');
    }
    ...
}
?>

 

 

Now, you can use this helper in any view:

 

<?php
   ...
   $this->lists()->makeLink($page);
   ...
?>