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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With