How do I get a service from the container directly, if I didn't/couldn't inject the service using DI?

后端 未结 1 1154
小鲜肉
小鲜肉 2021-01-20 05:32

I have a part of code where I\'m injecting two services $checker and $paginator by dependency injection. It works perfectly:

public         


        
1条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-01-20 06:02

    You need to add your dependencies so the service locator can find them.

    Add a method getSubscribedServices() to your controller class:

    public static function getSubscribedServices()
    {
        return array_merge(
            parent::getSubscribedServices(),
            [
                'checker' => Checker::class,
            ]
        );
    }
    

    If your controller class extends AbstractController you can simply do:

    $this->get('checker');
    

    If you want to do it in another type of class (e.g. a service that doesn't extend AbstractController), then you need to declare that your service implements the ServiceSubscriberInterface.

    use Symfony\Contracts\Service\ServiceSubscriberInterface;
    use Psr\Container\ContainerInterface;
    
    class FooService implements ServiceSubscriberInterface {
    
        public function __construct(ContainerInterface $locator)
        {
            $this->locator = $locator;
        }
    
        public static function getSubscribedServices() { /* same as before */ }
    
        public function get($service)
        {
            return $this->locator->get($service);
        }
    }
    

    ... and you would be able to do the same than you in the controller earlier.

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