为什么 Twig 在使用自定义视图助手时需要 __invoke 方法?

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

当我想在基于 ZF2 的项目中实现时在 Twig 模板中使用自定义视图助手时,我需要添加视图助手中的魔术方法 __invoke 方法;否则,Twig 模板引擎会抛出一个错误,提示无法调用视图助手的 __invoke 方法。

现在我想知道为什么我需要在视图助手中声明这个__invoke魔术函数?

查看文档:https://framework.zend.com/manual/2.1/en/modules/zend.view.helpers.advanced-usage.html

如果您希望您的助手能够像 PhpRenderer 的方法调用一样被调用,您还应该在您的助手中实现一个 __invoke() 方法。

这同样适用于 twig 渲染器,它正在尝试执行助手 class(使用调用作为快捷方式)

您可以看到 PHPRenderer 在哪里使用 __invoke() 作为助手的代理/快捷方式:

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;
}

我想 Twig 渲染器只是在做类似的事情,事实上我们可以在下面看到它是:

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