zf2 Creation of simple service and access it through viewhelper

烂漫一生 提交于 2019-11-28 06:03:16

An alternative, in PHP 5.4 only, without specific configuration, would be to use traits:

extract of module.config.php:

'view_helpers' => array(
    'invokables' => array(
        'myHelper' => 'Application\View\Helper\MyHelper',
    ),  

MyHelper.php:

<?php
namespace Application\View\Helper;

use Zend\ServiceManager\ServiceLocatorAwareInterface;  

class HeadScript extends \Zend\View\Helper\MyHelper implements ServiceLocatorAwareInterface
{
    use \Zend\ServiceManager\ServiceLocatorAwareTrait;

    public function __invoke()
    {
        $config = $this->getServiceLocator()->getServiceLocator()->get('Config');
        // do something with retrived config
    }

}

change the line $this->sm->getServiceLocator()->get('Application\Service\Service1'); in below method

class Abc extends AbstractHelper 
{
   protected $sm;

   public function test()
    {
        $this->sm->getServiceLocator()->get('Application\Service\Service1');
    }
    public function __construct($sm) {
        $this->sm = $sm;

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