简体   繁体   English

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

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

Just as the title says, i need to inject service locator in a custom listener in zf2, as i need to get a service there. 就像标题所说的那样,我需要在zf2的自定义侦听器中注入服务定位符,因为我需要在那里获取服务。

I searched for 2 hours both on google and on stackoverflow, but found nothing, so I dared to ask you. 我在Google和stackoverflow上搜索了2个小时,但一无所获,所以我敢问你。

Any ideas? 有任何想法吗?

Thank you a lot! 非常感谢!

you just need to make your listener implements the 'ServiceLocatorAwareInterface' adding this 'use' block at the top of your service class: 您只需要使您的侦听器实现“ ServiceLocatorAwareInterface”,并在服务类的顶部添加以下“ use”块即可:

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

then add the following property and methods to your class 然后将以下属性和方法添加到您的类中

/**
 * @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;
}

Then, create your listener service, it can be an Invokable or a Factory if you need other configuration. 然后,创建您的侦听器服务,如果需要其他配置,它可以是Invokable或Factory。

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

Zend Framework will now inject the service locator for you. Zend Framework现在将为您注入服务定位器。

I think the better way is to use the factory and don't give serivceManager inside listener. 我认为更好的方法是使用工厂,并且不要在监听器中提供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