繁体   English   中英

如何在zf2的自定义侦听器中注入服务定位器?

[英]How to inject service locator in a custom listener in zf2?

就像标题所说的那样,我需要在zf2的自定义侦听器中注入服务定位符,因为我需要在那里获取服务。

我在Google和stackoverflow上搜索了2个小时,但一无所获,所以我敢问你。

有任何想法吗?

非常感谢!

您只需要使您的侦听器实现“ ServiceLocatorAwareInterface”,并在服务类的顶部添加以下“ use”块即可:

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现在将为您注入服务定位器。

我认为更好的方法是使用工厂,并且不要在监听器中提供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);
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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