Question

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!

Was it helpful?

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.

OTHER TIPS

I think the better way is to use the factory and don't give serivceManager inside listener.

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);
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top