简体   繁体   中英

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). 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.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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