Syed Abidur Rahman Syed Abidur Rahman - 1 month ago 17
Twig Question

Why does Twig require the __invoke method while using custom view helper?

When I want to use my custom view helpers in the Twig template while implementing in the ZF2 based project, I need to add the magic method __invoke method in the view helper; otherwise, Twig template engine throw an error which says about unable to call the __invoke method of the view helper.

Now I want to know why I need to declare this __invoke magic function in the view helpers?

Answer

Check the docs: https://framework.zend.com/manual/2.1/en/modules/zend.view.helpers.advanced-usage.html

If you want your helper to be capable of being invoked as if it were a method call of the PhpRenderer, you should also implement an __invoke() method within your helper.

The same must apply with the twig renderer, it's trying to execute the helper class (using invoke as a shortcut)

You can see where the PHPRenderer is using __invoke() as a proxy / shortcut to the helpers:

https://github.com/zendframework/zend-view/blob/master/src/Renderer/PhpRenderer.php#L389

/**
 * Overloading: proxy to helpers
 *
 * Proxies to the attached plugin manager to retrieve, return, and potentially
 * execute helpers.
 *
 * * If the helper does not define __invoke, it will be returned
 * * If the helper does define __invoke, it will be called as a functor
 *
 * @param  string $method
 * @param  array $argv
 * @return mixed
 */
public function __call($method, $argv)
{
    $plugin = $this->plugin($method);
    if (is_callable($plugin)) {
        return call_user_func_array($plugin, $argv);
    }
    return $plugin;
}

I imagine the Twig renderer is just doing something similar, infact we can see below it is:

https://github.com/ZF-Commons/ZfcTwig/blob/master/src/ZfcTwig/View/TwigRenderer.php#L83

Comments