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.
