如何将自定义视图助手添加到Zend Framework 2(测试版4) [英] How to add custom view helpers to Zend Framework 2 (beta 4)

查看:93
本文介绍了如何将自定义视图助手添加到Zend Framework 2(测试版4)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我看过

I have looked at this example from the manual. Note that this is version 2 of the Zend Framework.

我创建了这个助手:

<?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',
            ),
        )),
    )),
);

但是在视图中执行此操作时,例如add.phtml

but when doing this in a view, for instance add.phtml

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

它将崩溃,表示找不到助手.

It will crash, saying it cannot find the helper.

但是,在相同的add.phtml文件中,我可以做

However, in the same add.phtml file I can do

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

并有权访问它,所以我猜名称空间应该正确吗?

and have access to it, so I guess the namespace should be right?

目前,我在Module.php中进行了注册,但是我也在其他地方尝试过.

Currently I register it in Module.php, but I have also tried elsewhere.

我的目标是可以访问模块中所有视图的视图助手,而不必在每个phtml文件中创建它的实例,也不必每次都在控制器中添加它.

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.

如何实现?谢谢.

推荐答案

ZF2转移到具有编程工厂的服务经理,而di用作后备工厂.

ZF2 moved to service managers with programmatic factories, while di used as fallback factory.

对于视图来说,现在有一个视图管理器,由于服务解析在找到工厂后就停止了,通过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.

您现在应该如何注册助手的示例,您可以在 ZfcUser模块配置

Example how you should register helpers now you can find in ZfcUser module config

这篇关于如何将自定义视图助手添加到Zend Framework 2(测试版4)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆