Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
529 views
in Technique[技术] by (71.8m points)

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

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

public function index(Request $request, Paginator $paginator, Checker $checker)
    {
        $result = ['a', 'b', 'c', 'd', 'e', 'f', 'g'];
        $partialResult = $paginator->getPartial($result, 0, 3);
        $checker->isValid('A');
        var_dump("test");
        die;
    }

Below the configuration on services.yaml file:

   paginator:
        public: true
        class: 'AppHelperPaginator'

    checker:
        public: true
        class: 'AppHelperChecker'
        arguments:
         $paginator: '@paginator'

But I'd like to inject for some reasons service by method:

$checker = $this->container->get('checker');

But it doesn't work. In previous versions Symfony like 3.4 it used to.

I'm receiving an error:

Service "checker" not found: event though it exists in the app's container, the container inside "AppControllerDefaultController" is a smaller service locator that only knows about the "http_kernel", "parameter_bag", "request_stack", "router", "session", and "twig" services. Try using dependency injection instead.

How should I solve this?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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 SymfonyContractsServiceServiceSubscriberInterface;
use PsrContainerContainerInterface;

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...