How can i inject dependencies to Symfony Console commands?

后端 未结 7 1041
醉话见心
醉话见心 2020-12-09 08:00

I\'m writing an open source application uses some Symfony components, and using Symfony Console component for interacting with shell.

But, i need to inject dependen

7条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-09 08:09

    Since Symfony 4.2 the ContainerAwareCommand is deprecated. Use the DI instead.

    namespace App\Command;
    
    use Symfony\Component\Console\Command\Command;
    use Doctrine\ORM\EntityManagerInterface;
    
    final class YourCommand extends Command
    {
        /**
         * @var EntityManagerInterface
         */
        private $entityManager;
    
        public function __construct(EntityManagerInterface $entityManager)
        {
            $this->entityManager = $entityManager;
    
            parent::__construct();
        }
    
        protected function execute(InputInterface $input, OutputInterface $output)
        {
            // YOUR CODE
            $this->entityManager->persist($object1);    
        }
    }
    

提交回复
热议问题