Symfony 6命令中使用EntityManagerInterface报错及解决方法
Symfony 6命令中注入EntityManagerInterface的问题与解决方法
问题场景
在Symfony 6中编写CleanDBCommand命令时,尝试通过构造函数注入EntityManagerInterface,但运行时触发类型错误。
原代码
#[AsCommand( name: 'app:cleanDB' )] class CleanDBCommand extends Command { private $em; public function __construct(EntityManagerInterface $entityManager) { $this->em = $entityManager; parent::__construct($entityManager); } protected function execute(InputInterface $input, OutputInterface $output): int { $date = new \DateTime('now'); $repo = $this->em->getRepository(User::class); $shortUrl = $repo->findBy(['createdAt'=>'<'.$date->format('Y-m-d')]); $io = new SymfonyStyle($input, $output); $io->success('You have a new command! Now make it your own! Pass --help to see your options.'); return Command::SUCCESS; } }
报错信息
Symfony\Component\Console\Command\Command::__construct(): Argument #1 ($name) must be of type ?string, Container6Yp8i34\EntityManagerGhostE8260f8 given, called in /.../app/src/Command/CleanDBCommand.php on line 28
解决方案
问题根源在于父类Command的构造函数要求传入命令名称(字符串或null),但原代码错误地将EntityManagerInterface实例传给了父类构造。
只需修改父类构造的传参,将$entityManager替换为命令名称:
修改前
parent::__construct($entityManager);
修改后
parent::__construct('app:cleanDB');
这样既完成了EntityManagerInterface的依赖注入,又符合父类构造函数的参数要求,命令即可正常运行。
内容的提问来源于stack exchange,提问作者Phani Shashank
相关产品推荐
相关产品推荐

