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

前端 未结 1 765
小鲜肉
小鲜肉 2021-01-28 19:07

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 som         


        
相关标签:
1条回答
  • 2021-01-28 19:33

    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.

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