【问题标题】:How to inject service locator in a custom listener in zf2?如何在 zf2 的自定义侦听器中注入服务定位器?
【发布时间】:2014-04-24 14:57:11
【问题描述】:

正如标题所说,我需要在 zf2 的自定义侦听器中注入服务定位器,因为我需要在那里获得服务。

我在google和stackoverflow上搜索了2个小时,都没有找到,所以我才敢问你。

有什么想法吗?

非常感谢!

【问题讨论】:

  • 您目前如何以及在何处连接您的听众?您能否编辑您的问题以包含一些代码?
  • 当然,对不起,但监听器不是问题,问题在于将服务定位器附加到监听器
  • 没关系,我解决了,我会尽快发布答案

标签: php zend-framework2 service-locator


【解决方案1】:

您只需让您的侦听器实现“ServiceLocatorAwareInterface”,在您的服务类顶部添加此“使用”块:

use Zend\ServiceManager\ServiceLocatorAwareInterface,
    Zend\ServiceManager\ServiceLocatorInterface;

然后将以下属性和方法添加到您的类中

/**
 * @var ServiceLocatorInterface
 */
protected $serviceManager;

/**
 * 
 * @param ServiceLocatorInterface $serviceLocator
 */
public function setServiceLocator(ServiceLocatorInterface $serviceLocator)
{
    $this->serviceManager = $serviceLocator;
}

/**
 * 
 * @return \Zend\ServiceManager\ServiceLocatorInterface
 */
public function getServiceLocator()
{
    return $this->serviceManager;
}

然后,创建您的侦听器服务,如果您需要其他配置,它可以是 Invokable 或 Factory。

'Path\To\MyListener' => new MyListener(),

Zend Framework 现在将为您注入服务定位器。

【讨论】:

    【解决方案2】:

    我认为更好的方法是使用工厂并且不要在监听器中提供 serivceManager。

    class FooListenerFactory implements FactoryInterface
    {
        /**
         * @param ServiceLocatorInterface $serviceLocator
         * @return FooListener
         */
        public function createService(ServiceLocatorInterface $serviceLocator)
        {
            /* @var $entityManager EntityManager */
            $entityManager = $serviceLocator->get('what_u_need');
    
            return new FooListener($entityManager);
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2015-12-01
      • 2013-01-21
      • 1970-01-01
      • 2016-12-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-09-21
      相关资源
      最近更新 更多