Writing a Custom View Helper

I wanted to write a set of functions available to me from the view to do some repetative tasks, such as converting a number to a set monetary format. It was obvious to me that I needed to write a custom view helper, but I had some small problems along the way that are worth mentioning.

The docs on the Zend Framework site on writing custom view helpers (here) are a little misleading. They say that as long as you follow the naming rules, that your helper will autoload and instanciate. The documentation give an example where the class is named My_View_Helper_SpecialPurpose. Having written my code, I found that the best way to get the class to autoload is to put the script in the views/helpers directory, and name it Zend_View_Helper_SpecialPurpose. Everything then worked with no changes needed to my bootstrap.

For those of you interested, here is my code:


class Zend_View_Helper_ToPounds extends Zend_View_Helper_Abstract
	* Returns an integer value converted to pounds
	* @return string
	* @param $int Integer value to convert to £ format
	* @access public
	public function toPounds($int)
		return htmlentities('£'.number_format($int, 2, '.', ','));

I can now call the function from within any view using:

<?php echo $this->toPounds(100); ?>

I hope that helps somebody.

Your Comments are Awesome, Please Leave Them!

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

WordPress.com Logo

You are commenting using your WordPress.com 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