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

半城伤御伤魂 提交于 2019-12-12 03:47:25

问题


NOTE: This is an old question and the answers here no longer works (since beta5). See this question on how to do it with ZF2 stable version.

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

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

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

It will crash, saying it cannot find the helper.

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?

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

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.

How can this be achieved? Thanks.


回答1:


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

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.

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




回答2:


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


来源:https://stackoverflow.com/questions/11062923/how-to-add-custom-view-helpers-to-zend-framework-2-beta-4

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!