Custom View Helper in Zend Framework

Zend Framework which is built on MVC design pattern has also provided lots of it’s accessories. The view helper is one of them.

 

The view helper, as it named, is to help the view to complete it’s work. It’s major role is to package the html code and sometimes with model data.

 

Here I will use a simple but useful helper – Image Helper to show you how to build your own one.

 

First the application structure :

 

 

Now is the code :

 

[codesyntax lang=”php”]

// Bootstrap.php

// Get viewRenderer
$viewRenderer = Zend_Controller_Action_HelperBroker::getExistingHelper('viewRenderer');

// initialize the view
$viewRenderer->initView($myViewBasePath);
$view = $viewRenderer->view;

// Path and prefix of custom view helper
$view->addHelperPath('Kbs/View/Helper/', Kbs_View_Helper_);

[/codesyntax]

 

[codesyntax lang=”php”]

// Image Helper : Kbs/View/Helper/Img.php

require_once('Zend/View/Helper/Abstract.php');

class Kbs_View_Helper_Img extends Zend_View_Helper_Abstract
{
    public function img($src, $width, $height, $alt = '', $options = array())
    {
        if (empty($alt)) {
            // make sure alt is not empty for SEO
            throw new Zend_View_Exception('Alt attribute should be filled.');
        }

        $basepath = $this->view->serverUrl() . '/public/img/';
        $img = '<img src="' . $basepath . $src . '" width="' . $width . '" '
             . 'height="' . $height . '" alt="' . $alt . '" />';

        return $img;
    }
}

[/codesyntax]

 

[codesyntax lang=”php”]

// index.phtml
echo $this->img('example.jpg', 100, 100, 'This is the example');

[/codesyntax]

 

Isn’t it easy enough?

Posted in Zend Framework | Tagged | Leave a comment