zf2 Creation of simple service and access it through viewhelper

后端 未结 2 851
轮回少年
轮回少年 2020-12-08 12:26

I am trying to create a simple service in zf2 which I can access using in viewhelper

Step1. I have craeted a class in src/Application/Service/Servic

相关标签:
2条回答
  • 2020-12-08 12:36

    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;
    
        }
    }
    
    0 讨论(0)
  • 2020-12-08 12:57

    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
        }
    
    }
    
    0 讨论(0)
提交回复
热议问题