Zend Framework – create custom view helper

Zend Framework is not as popular as Symfony, but it’s also nice and have a lot of nice features. One of them is view helpers – classes and objects which we can use in templates to make specific thinks. Zend has few build-in helpers, for example to use absolute app directory, set or receive HTML doctype, use partials templates or use authentication data. Sometimes we can (or maybe should) create our view helper to avoid repetition of the code. It’s simple, let’s try.

When and why should we create our view helpers?

When we should create our view helper? It’s simple: always, when we can move some repeated code – instead of using it in many templates, write only once in helper class. Simple example can be something to create thumbnails on our application templates. We have array with images and names for titles and want create grid with that images. Of course, we can use the same code in many places, but what we we have to change it? We must check and change it in any place – yes, we can use search and replace, but sometimes is not enough. Better choice is to create helper and use it in only one line. If we must change something, just change in class, not in many templates.

Create helper class

First, we must create helper class, for example in one of or modules – say MyModule/src/MyModule/View/Helper/ThumbnailsHelper.php – it will file with our class. We should extend AbstractHelper to use magic __invoke method in templates, let’s try simple example for thumbnails:

 

Register our helper

Of course we can do the same using partials templates – and in many cases it will be better choice, but it’s only example. Second think is to register our view helper in our module. Without that, Zend will not allow us to use magic function in templates. Edit file MyModule/module.config.php and add code for our new helper:

 

Use helper in templates

Save and… it’s all. We can now use view helper in our templates:

 

What about using view helpers in controllers? It’s possible, but not recommended, because we must use ServiceLocator to get our helper (and ServiceLocatorAwareInterface is deprecated from Zend Framework 3). We should use it only in templates.

One Reply to “Zend Framework – create custom view helper”

Leave a Reply