Search code examples
phpzend-framework2service-locator

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.

I searched for 2 hours both on google and on stackoverflow, but found nothing, so I dared to ask you.

Any ideas?

Thank you a lot!


Solution

  • you just need to make your listener implements the 'ServiceLocatorAwareInterface' adding this 'use' block at the top of your service class:

    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.

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

    Zend Framework will now inject the service locator for you.