Skip to content

How to Create Custom View Helper in ZF2

Last updated on December 21, 2022

In this post I will show you how to create a custom view helper in ZF2, writing a custom view helper in zf2 is very easy thanks to zf2 authors.

Here in this example, I am goanna create StaticFileVersioning Module, you can place this module in two different places, one is the vendor’s directory and another option is the module directory.

I prefer to keep this module in the vendors’ directory. So my folder structure will be webroot/vendor/StaticFileVersioning. You can download it at any time sample files from the below URL.

https://github.com/iarjunphp/Static-File-Versioning—zf2-cache-buster-module

Create a StaticFileVersioning/src/StaticFileVersioning/View/Helper/StaticVersion.php Class.

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

class StaticVersion extends AbstractHelper {
    public function __invoke($path,$prefix = '?v=',$suffix = '') {
		 $version = filemtime('..'.$path);
		 $version = md5($version);
		 return $path . $prefix . $version . $suffix;
    }
}

configuring it as an invokable in StaticFileVersioning/config/module.config.php

return array(
    'view_helpers' => array(
        'invokables' => array(
            'StaticVersion' => 'StaticFileVersioning\View\Helper\StaticVersion',
        )
    )
);

Call it in the view

$this->staticVersion("/public/css/bootstrap.css");
// output will be /public/css/bootstrap.css?v=d753e357740e330fae27bd2390734ffd

I hope this tutorial helps you please don’t forget to give us your feedback in the comments.

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments