简体   繁体   English

如何将自定义视图助手添加到Zend Framework 2(测试版4)

[英]How to add custom view helpers to Zend Framework 2 (beta 4)

NOTE: This is an old question and the answers here no longer works (since beta5). 注意:这是一个老问题和答案在这里不再有效(因为beta5的)。 See this question on how to do it with ZF2 stable version. 请参见关于如何使用ZF2稳定的版本做的问题。

I have looked at this example from the manual. 我已经看过这个例子从手动。 Note that this is version 2 of the Zend Framework. 请注意,这是Zend Framework的版本2。

I create this helper: 我创建了这个助手:

<?php
namespace Mats\Helper;    
use Zend\View\Helper\AbstractHelper;    
class SpecialPurpose extends AbstractHelper
{
    protected $count = 0;    
    public function __invoke()
    {
        $this->count++;
        $output = sprintf("I have seen 'The Jerk' %d time(s).", $this->count);
        return htmlspecialchars($output, ENT_QUOTES, 'UTF-8');
    }
}
?>

and then try to register it like this: 然后尝试像这样注册它:

return array(
    'di' => array('instance' => array(
        'Zend\View\HelperLoader' => array('parameters' => array(
            'map' => array(
                'specialpurpose' => 'Mats\Helper\SpecialPurpose',
            ),
        )),
    )),
);

but when doing this in a view, for instance add.phtml 但在视图中执行此操作时,例如add.phtml

<?php echo $this->specialPurpose(); ?>

It will crash, saying it cannot find the helper. 它会崩溃,称它无法找到帮手。

However, in the same add.phtml file I can do 然而,在同add.phtml文件我可以做

<?php $helper = new Mats\Helper\SpecialPurpose(); ?>

and have access to it, so I guess the namespace should be right? 并可以访问它,所以我猜名称空间应该正确吗?

Currently I register it in Module.php, but I have also tried elsewhere. 目前,我在Module.php中进行了注册,但是我也在其他地方尝试过。

My goal is to have access to the view helper in all views in my module, without having to create an instance of it in each phtml file, and not having to add it every time in the controller. 我的目标是有机会获得在我的模块中的视图的帮手,而不必在每个PHTML文件来创建它的一个实例,而不必每次都将其添加在控制器中。

How can this be achieved? 如何做到这一点? Thanks. 谢谢。

ZF2 moved to service managers with programmatic factories, while di used as fallback factory. ZF2转移到程序化工厂的服务经理,而di用作备用工厂。

For view there is view manager now and as service resolution stops as soon as it found factory, helpers configured via di no longer work. 对于视图,现在有一个视图管理器,由于服务解析在找到工厂后就停止了,通过di配置的助手不再起作用。

Example how you should register helpers now you can find in ZfcUser module config 现在您可以在ZfcUser模块配置中找到如何注册助手的示例

Add custom helper is very simple, just add one line to your module config file like this: 添加自定义帮助程序非常简单,只需向模块配置文件添加一行即可,如下所示:

return array(
    'view_manager' => array(
        'helper_map' => array(
            'specialPurpose' => 'Mats\Helper\SpecialPurpose',
        ),
    ),
);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM