How to inject services dynamically into Symfony Command based on command argument.

好久不见. 提交于 2021-02-05 11:26:36

问题


I have a Symfony command that takes an argument which serves as a locator to a specific service required (based on that argument).

ie.

bin/console some:command service-locator-id

with Symfony 2.8 you can simply fetch the service from the container

$service = $this->container->get($input->getArgument('service-locator-id'));

With Symfony 3.4 however, the container is deprecated and we should be using Dependency Injection.

How do I inject the service that I require based on the argument being passed into the Command ?


回答1:


Ok, I was finally able to figure this out using the service locator documentation.

https://symfony.com/doc/3.4/service_container/service_subscribers_locators.html

basically,

class MyCommand extends ContainerAwareCommand implements ServiceSubscriberInterface
{

    private $locator;

    private $serviceId;

    public static function getSubscribedServices()
    {
        return [
            'service-locator-id-one' => ServiceClassOne::class,
            'service-locator-id-two' => ServiceClassTwo::class,
        ];
    }

    /**
     * @required
     * @param ContainerInterface $locator
     */
    public function setLocator(ContainerInterface $locator)
    {
        $this->locator = $locator;
    }

    protected function configure()
    {
        $this
        ->setName('some:command')
        ->addArgument('service-locator-id', InputArgument::REQUIRED, 'Service Identifier');
    }

    /**
     * 
     * @return void|MyServiceInterface
     */
    private function getService()
    {
        if ($this->locator->has($this->serviceId)) {
            return $this->locator->get($this->serviceId);
        }
    }
}

Works perfectly.



来源:https://stackoverflow.com/questions/52808021/how-to-inject-services-dynamically-into-symfony-command-based-on-command-argumen

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!