Symfony 4: doctrine in command

后端 未结 6 1857
[愿得一人]
[愿得一人] 2021-01-05 00:44

I am using symfony 4 and I want to access a repository for an entity if I am in the Command class. There is not a function getDoctrine or something..

I

6条回答
  •  醉梦人生
    2021-01-05 01:24

    The official Symfony 4 advice is to autowire only what you need. So instead of injecting ContainerInterface and requesting an EntityManager from that, inject EntityManagerInterface directly:

    use Doctrine\ORM\EntityManagerInterface;
    
    class YourCommand extends Command
    {
    
        private $em;
    
        public function __construct(EntityManagerInterface $em)
        {
            parent::__construct();
            $this->em = $em;
        }
    
        protected function execute(InputInterface $input, OutputInterface $output)
        {
            $this->em->persist($thing);
            $this->em->flush();
        }
    
    }
    

提交回复
热议问题