Custom Zend Framework 2 View Helper
In this article, you will learn how to create a custom view helper in Zend Framework 2. A concrete example will be used; a helper which generates links for a subdomain, intended for storing static files. This is especially useful if you wish to use a Content Delivery Network (CDN). With very little modification, the helper can be made generic to support links to subdomains for all purposes.
The Helper Class
Let us begin by creating the helper class. It can be added within any module, but a suitable place would be within the Application module, provided that you made use of the Skeleton Application.
namespace Application\View\Helper;
use Zend\View\Helper\AbstractHelper;
use Zend\Http\Request;
class StaticLink extends AbstractHelper {
const SUBDOMAIN = 'static';
const IMAGE = 'images';
const CSS = 'css';
const JS = 'js';
const VIDEO = 'videos';
const OTHER = 'other';
protected $request;
public function __construct(Request $request) {
$this->request = $request;
}
public function __invoke($file_name, $subfolder = null, array $subdirectories = array()) {
$static_url = 'http://' . self::SUBDOMAIN . '.' . $this->request->getUri()->getHost() . '/';
if (!empty($subfolder)) {
$static_url .= $subfolder . '/';
}
if (is_array($subdirectories) && !empty($subdirectories)) {
foreach ($subdirectories as $subdirectory) {
$static_url .= $subdirectory . '/';
}
}
$static_url .= $file_name;
return $static_url;
}
public function setRequest($request) {
$this->request = $request;
}
public function getRequest() {
return $this->request;
}
}
There are a few things to discuss about the above code. Firstly, the class extends the AbstractHelper class, which implements HelperInterface. All the class does is to provide a property for the view object and a getter and setter method. Optionally, one can simply implement HelperInterface, but normally the functionality provided within the abstract class is sufficient.
A series of constants are defined within the above class. The purpose of the constants is to provide an easy way to access directory names for the various types of resources. This way, one can make use of these constants when using the helper instead of hard coding directory names for every use of the helper.
Because we need access to the host name, the Zend\Http\Request object will be injected into the helper’s constructor. As a result, a little more work has to be done before the helper is ready for use, but we will get back to that in a moment. The request object is stored as a field variable and a getter and setter is also implemented.
The implementation of the __invoke method means that the class can be used as if it were a method. The method takes three parameters where two are optional; the name of the file to link to, a subfolder, and an array of subdirectories. The subfolder – if any – is appended to the host name, whereafter any subdirectories are appended. Lastly, the file name is appended. After configuring the helper, there will be an example that further explains the meaning of each parameter. The method’s logic itself is quite straightforward and is not of importance in order to learn how to create custom view helpers, and thus it will not be discussed.
Configuring the Helper
Before using the helper, it must be registered. Because we have a dependency in the form of a Zend\Http\Request object, we will be injecting this dependency by using a factory. If we did not have any dependencies, a simply invokable should be used because no initialization would be required. For more information about the service manager and its various features, please consider reading our article about the service manager. While there are various ways to configure the helper, we will be using a configuration file, which is the most common approach. Even in regards to configuration files, there are several ways to go about it; one can add a view_manager key with a nested factories key either to the main configuration file located at config/application.config.php or to a module’s config/module.config.php. It can also be configured within the Module class’ getViewHelperConfig method by returning an array.
The way we will do it, though, is to use a separate configuration file that only configures view helpers. For this purpose, the Zend\ModuleManager\Feature\ViewHelperProviderInterface defines a getViewHelperConfig method. While implementing this interface in the Module class is not strictly necessary, it is good practice. The module manager will check to see if the class either implements the interface or simply provides a method with that name. For a discussion about other methods in the Module class and the use of interfaces, please refer to our article about eliminating module dependencies.
To keep the class simple, we will not simply return an array from the getViewHelperConfig method. Rather, the configuration will be stored in a different file within the config folder. This file will then be read and returned. Please consider the code below.
namespace Application;
use Zend\ModuleManager\Feature\ConfigProviderInterface;
use Zend\ModuleManager\Feature\AutoloaderProviderInterface;
use Zend\ModuleManager\Feature\ViewHelperProviderInterface;
class Module implements ConfigProviderInterface, AutoloaderProviderInterface, ViewHelperProviderInterface
{
public function getConfig()
{
/* ... */
}
public function getAutoloaderConfig()
{
/* ... */
}
public function getViewHelperConfig() {
return include(__DIR__ . '/config/view.config.php');
}
}
The getViewHelperConfig method simply includes and returns the below configuration file.
use Application\View\Helper\StaticLink;
return array(
'factories' => array(
'staticLink' => function($sm) {
return new StaticLink($sm->getServiceLocator()->get('Request'));
}
)
);
The key in the factories array is the name by which we will refer to our custom helper from within view scripts. Note that it is possible for other modules to overwrite this entry because the module manager merges module configurations. If this were to occur, then the order in which modules are loaded decides which helper will actually be available for a given name. The service manager that is passed to the factory (closure or anonymous function) is a specialized service manager for the view helper. Therefore we need to first access the “main” service manager before we can fetch the request object from it. This object is then injected into the view helper, which is returned.
Using the View Helper
Voilá! The view helper is now ready for use from within view scripts.
echo $this->staticLink('my_picture.jpg', Application\View\Helper\StaticLink::IMAGE, array('profiles', 'admins'));
// Output: http://static.mydomain.com/images/profiles/admins/my_picture.jpg
Remember the __invoke magic method? Its magic is demonstrated above where the class is used as a method. The first parameter is the name of the file to link to. The second is the subfolder where we make use of one of the constants defined within the helper class. The third and last parameter is an array of subdirectories, which are added in-between the subfolder and file name.
Downloads and Alternatives
In this article, we walked through the process of installing the view helper by editing a configuration file. It is also possible to install the view helper by installing a module; while this solution may not be as elegant, it is certainly easier and more of a “plug and play” solution. Such a module can be downloaded from my GitHub repository. Please note that performance can be improved by not using a standalone module to install the view helper, but using the installation approach discussed in this article instead.
Here is what you will learn:
- Understand the theory of Zend Framework in details
- How to implement an enterprise-ready architecture
- Develop professional applications in Zend Framework
- Proficiently work with databases in Zend Framework
- ... and much more!

8 comments on »Custom Zend Framework 2 View Helper«
Hi, I’ve followed your instructions but when i execute it, i recive code above:
Catchable fatal error: Argument 1 passed to Front\view\helper\FormHelper::__construct() must be an instance of Zend\Http\Request, none given, called in C:\xampp\htdocs\zirtrex\vendor\zendframework\zendframework\library\Zend\ServiceManager\AbstractPluginManager.php on line 170 and defined in C:\xampp\htdocs\zirtrex\module\Front\src\Front\view\helper\FormHelper.php on line 17
what’s the wrong?
i think i’m doing fine.
Hello Rafael,
It seems that your view helper FormHelper expects an instance of Zend\Http\Request as its constructor’s single parameter – just like in my example above. Is it on purpose that the constructor expects this parameter? If so, then you need to inject it, and otherwise you can simply remove it to fix your error. If you want to have the request object available in your view helper, then you can see how you can do so in my view.config.php above.
Best regards,
Bo Andersen
I to have followed this verbatim from a fresh install. I get the same error requiring Request to be given to the method on __construct. The request object is not available in the view scope, I believe. I hoped this page, would show me some magic to access the request method in the view.
As I wrote in my response to Rafael, you have to inject the Request object into the view helper, given that you are making a custom view helper. To do this, you can create a new factory when configuring the service manager, which will then inject the Request object that is fetched from the service manager. Then the object will be available to you in your view helper.
If you are not implementing a custom view helper, you can also send it to the view by returning it in an array in the controller action ($this->request).
thanks for the good tutorials, I hope you can help me with the below:
I built a custom view helper to display a login/registration view script with forms site-wide, for convenience I just call the custom view helper from the layout like $this->loginRegister().
However I found it very complex to get access to the ZF2 standard view helpers using this method, I had to manually configure it to get access to the form helpers and now I have another problem, the url helper ($this->url()) is also not available in my view script, or something else is wrong because I get the error ‘Zend\View\Exception\RuntimeException’ with message ‘No RouteStackInterface instance provided’
Sorry for pasting my code here but please tell me if this is the wrong approach because to me it looks really overly complex and I hope there is a simpler way to accomplish this.
Hi,
Thanks for the nice post! Could you please explain how we could add some database functionality for the helper?
Thanks.
C.
Hello Chris,
I do not know your particular use case for doing so, but generally speaking, I would say that accessing the database directly from within a view helper is not good practice. Nevertheless, below is how you should be able to do it.
When you instantiate the view helper in your factory, you can pass the database adapter to the view helper’s constructor like in the following example.
Now update your view helper’s constructor to accept a database adapter object.
Add a variable after your class declaration:
Now you should be able to access the database throughout your view helper. I hope it works for you. Best of luck! :-)
Hi Bo,
Very well explained! Thank you for the solution.
C.