Create a view helper in zend framework 2

This article looks at how you can create a view helper in zend framework 2.

View helpers are used to perform logic that is repeated within your views so you that you don't need to repeat code, or clutter your views with business logic. 

In this example I'm going to create a hello world view helper that will output a string when run.

To start with let's create the view helper file, where you place this is flexible but my recommendation is the following:

  • module
    • Application
      • config 
      • src
        • Application
          • Controller 
          • View
            • Helper
              • HelloWorldHelper.php

Here's a basic structure for the view helper code:

namespace Application\View\Helper;
use Zend\View\Helper\AbstractHelper;

class AutoEscapeHelper extends AbstractHelper
    public function __invoke()
        // business logic
        return 'hello world';

Next we need to register our view helper, to do this we set it as an invokable within the module.config.php file (in this case, the application module):

'view_helpers' => array(
        'invokables'=> array(
            'AutoEscapeHelper' => 'Application\View\Helper\HelloWorldHelper'

Finally we can use our new view helper within a view (phtml) file by calling it like so:

echo $this->helloWorldHelper();

The result should be 'hello world' printed out to the page. Note you could also pass variables into the function by adding parameters to the __invoke function. 

Sign Up
comments powered by Disqus

Popular Tags

Need a web developer?

If you'd like to work with code synthesis on your next project get in touch via the contact page.