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

后端 未结 1 1410
野趣味
野趣味 2021-02-15 11:55

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

Inside the controller it\'s easy:

$this->getServiceL         


        
相关标签:
1条回答
  • 2021-02-15 12:33

    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.

    0 讨论(0)
提交回复
热议问题