Aug 122012
 

This post will show you how to create a simple view helper in Zend Framework 2.

In this example, our view helper will simply return the full, absolute URL of the current page/request.

<?php
// ./module/Application/src/Application/View/Helper/AbsoluteUrl.php
namespace Application\View\Helper;
 
use Zend\Http\Request;
use Zend\View\Helper\AbstractHelper;
 
class AbsoluteUrl extends AbstractHelper
{
    protected $request;
 
    public function __construct(Request $request)
    {
        $this->request = $request;
    }
 
    public function __invoke()
    {
        return $this->request->getUri()->normalize();
    }
}

You’ll notice that this particular helper has a dependency — a Zend\Http\Request object. To inject this, we’ll need to set up a factory with the initialization logic for our view helper:

<?php
// ./module/Application/Module.php
namespace Application;
 
use Application\View\Helper\AbsoluteUrl;
 
class Module
{
    public function getViewHelperConfig()
    {
        return array(
            'factories' => array(
                // the array key here is the name you will call the view helper by in your view scripts
                'absoluteUrl' => function($sm) {
                    $locator = $sm->getServiceLocator(); // $sm is the view helper manager, so we need to fetch the main service manager
                    return new AbsoluteUrl($locator->get('Request'));
                },
            ),
        );
    }
 
     // If copy/pasting this example, you'll also need the getAutoloaderConfig() method; I've omitted it for the sake of brevity.
}

That’s it! Now you can call your helper in your view scripts:

The full URL to the current page is: <?php echo $this->absoluteUrl(); ?>

Note: I’ll be covering the details of the getViewHelperConfig() method and how ZF2 uses the ServiceManager to handle view helpers, controller plugins, etc in a later post.

  10 Responses to “Creating a simple view helper in Zend Framework 2”

  1. Before in beta cycle (I can’t remember when I stopped upgrading) we were able to register those helpers to the plugin broker from the module configuration file. Is that still possible? And which solution is the better?

  2. Can you give an example of register the same view helper via DI (in module_config) ?

  3. Hey Guy, could you please give some example of how can i use some viewhelper from another module? Thaks.

  4. Yes, an example “of how can i use some viewhelper from another module” would be very nice. There is a way to realize that? Many thanks!

  5. How could I call a method of the view helper from an action controller?

    I’ need to set some custom parameters for it from the action controller and can not figure out how.

    Thanks in advance

  6. Hey Evan, Thanks for your zf2 posts, they have been really helpful. I wanted to ask for your advice. If I wanted to make a sub navigation would I write a view helper and put it only on the pages I need it?

    Thanks!

  7. Hi, How I use a database table model inside view helper? Thanks in advance

  8. Hi, may be its handier like this ‘view_helpers’ => array( ‘invokables’ => array( ‘specialPurpose’ => ‘Application\View\Helper\SpecialPurpose’, ), ‘factories’ => array( ‘absoluteUrl’ => function($sm) { $locator = $sm->getServiceLocator(); // $sm is the view helper manager, so we need to fetch the main service manager return new Application\View\Helper\AbsoluteUrl($locator->get(‘Request’)); }, ), ), in module.config.php Bye

  9. good morning! please can u tell me how to use servicelocator to get authservice in a viewhelper?? thank you in advance :)

  10. A word to the wise. If you’re creating an AbsoluteUrl factory like this, make sure you remove this entry from module.config.php:

    ‘view_helpers’ => array( ‘invokables’ => array( ‘absoluteUrl’ => ‘Application\View\Helper\AbsoluteUrl’, …

    I had an entry like this for my view helper before I modified to pass a Request object to it, and I got “Argument 1 must be an instance of Zend\Http\Request, none given” errors. Looks like the invokables entry in module.config.php overrides the factories entry in Module.php.

 Leave a Reply

(required)

(required)

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre user="" computer="" color="" escaped="">