Zend Framework Custom View Helper

Creating custom helper in new Zend Framework edition 1.9 in few easy steps.
Let’s assume that we need to fetch some data from database
but we do not need them in all view files.

We need to insert this line in application/config.ini to register path to helpers:

application/configs/application.ini
resources.view.helperPath = APPLICATION_PATH “/views/helpers”

First create model which will give you an array,
in my example it’s list of states, which you will call in you helper file:

application/models/DbTable/States.php

class Model_DbTable_States extends Zend_Db_Table_Abstract
{
protected $_name = 'state_list';
 
public function getStates()
{
 
$row = $this->fetchAll();
if (!$row) {
throw new Exception("No States");
}
 
$row = $row->toArray();
 
return $row;
}
}

Class needs to begegins with “Zend_View_Helper_”
That is why it is “view helper” and it cannot be called in controller or model files,
if you do that you will get error that “method deoesn’t exists”.

application/view/helpers/State.php

class Zend_View_Helper_State
{
protected $_list;
 
public function state()
{
$state = new Model_DbTable_States();
return $this->_list->getStates();
 
}
}

After that and make a list of states in:

application/layouts/sidebar.phtml

<ul>
 	<li style="list-style-type: none;">
<ul>< ?php foreach ($this->state() as $item):?>
 	<li>< ?php echo $item['state']?></li>
</ul>
</li>
</ul>
< ?php endforeach;?>

and call it in main layout file:

application/layouts/layout.phtml

< ?php echo $this->partial('sidebar.phtml');
?>

In this case you will get content from your helper file in all views which will render main layout file from application/layouts/layout.phtml.
However, if you wish to call your helper in particular view all you need to do is to call the helper in view file:

< ?php $this->state();
?>