Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ZF2: how do I get ServiceManager instance from inside the custom class

I'm having trouble figuring out how to get ServiceManager instance from inside the custom class.

Inside the controller it's easy:

$this->getServiceLocator()->get('My\CustomLogger')->log(5, 'my message');

Now, I created a few independent classes and I need to retrieve Zend\Log instance inside that class. In zend framework v.1 I did it through static call:

Zend_Registry::get('myCustomLogger');

How can I retrieve the My\CustomLogger in ZF2?

like image 577
user2033934 Avatar asked Jul 26 '13 18:07

user2033934


1 Answers

Make your custom class implement the ServiceLocatorAwareInterface.

When you instantiate it with the ServiceManager, it will see the interface being implemented and inject itself into the class.

Your class will now have the service manager to work with during its operations.

<?php
namespace My;

use Zend\ServiceManager\ServiceLocatorAwareInterface;
use Zend\ServiceManager\ServiceLocatorAwareTrait;

class MyClass implements ServiceLocatorAwareInterface{
    use ServiceLocatorAwareTrait;


    public function doSomething(){
        $sl = $this->getServiceLocator();
        $logger = $sl->get( 'My\CusomLogger')
    }
}

// later somewhere else
$mine = $serviceManager->get( 'My\MyClass' );

//$mine now has the serviceManager with in.

Why should this work?

This works only in the context of the Zend\Mvc, which I assume you're using because you mentioned a controller.

It works because the Zend\Mvc\Service\ServiceManagerConfig adds an initializer to the ServiceManager.

$serviceManager->addInitializer(function ($instance) use ($serviceManager) {
    if ($instance instanceof ServiceLocatorAwareInterface) {
        $instance->setServiceLocator($serviceManager);
    }
});

Give it a try and let me know what happens.

like image 193
Jerry Saravia Avatar answered Oct 15 '22 05:10

Jerry Saravia