Syed Abidur Rahman Syed Abidur Rahman - 4 years ago 410
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 Source

Check the docs:

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:

 * 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:

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download