Skip to content

Custom View Helper

Sakya edited this page Apr 19, 2021 · 2 revisions

All PHP class that output as html can be place in View\Helper namespace.
All helper will be register during application bootstrap ( $application->run() ) and can be call in all phtml file.

View Helper are register in the configuration using aliases and factories.

  • entry in aliases is use to calling the helper inside phtml. e.g a helper with test alias will be called using $this->test()
  • entry in factories is use to define how this view helper class created. e.g Some helper require user session access.

Configuration example

return [
   view_helpers => [
       aliases => [
           "test" => View\Helper\TestView::class
       ],
       factories => [
           View\Helper\TestView::class => View\Helper\Factory\TestViewFactory::class
       ]
   ]
]

A helper must be invokable, this is a requirement for any class register with Dependency Injection (DI)

class TestView {
   public function __invoke() {
      // do something
   }
}

// calling in phtml
$this->test();

Builtin View\Helper is exist in the default configuration, check the source code to learn how to write a View Helper.

  • url : url string builder complete with query
  • flash : flash message for use mainly after POST
  • csrf : csrf token generator

Note that our builtin phprenderer currently not allow one view helper accessing other view helper.
To enable this function use Laminas PHP Renderer and Laminas View is encourage.

Laminas PHP Renderer

When using Laminas PHP Renderer combine with Laminas View, their structure allow for one view helper accessing other view helper with little effort.
The only drawback is you cannot debug ( print_r, var_dump, etc ) the view helper class cause it require a lot of memory.

To make sure view helper can access other view helper.

namespace View\Helper;
use Laminas\View\Helper\AbstractHelper;

# class must extends AbstractHelper
class TestView extends AbstractHelper {
   public function __invoke() {
      return $this;
   }

   public function render() {
      // Accessing other Helper e.g url
      // getView() will return the PHP renderer, from there you can access another view helper by their alias
      $this->getView()->url();
   }
}

When using Laminas Php Renderer, if View Helper Class doesn't require a specific Factory, then pass InvokableFactory as their Factories. Do to internal structure using DI\create will not works.

use Laminas\ServiceManager\Factory\InvokableFactory;

return [
   view_helpers => [
       aliases => [
           "test" => View\Helper\TestView::class
       ],
       factories => [
           View\Helper\TestView::class => InvokableFactory::class
       ]
   ]
];
Clone this wiki locally