Symfony2 - 如何在自定义控制台命令中访问服务?

2022-01-11 00:00:00 command console php symfony

我是 Symfony 的新手.我创建了一个自定义命令,其唯一目的是从系统中擦除演示数据,但我不知道如何执行此操作.

I am new to Symfony. I have created a custom command which sole purpose is to wipe demo data from the system, but I do not know how to do this.

在控制器中我会这样做:

In the controller I would do:

$nodes = $this->getDoctrine()
    ->getRepository('MyFreelancerPortfolioBundle:TreeNode')
    ->findAll();

$em = $this->getDoctrine()->getManager();
foreach($nodes as $node)
{
    $em->remove($node);
}
$em->flush();

从我得到的命令中的 execute() 函数执行此操作:

Doing this from the execute() function in the command I get:

Call to undefined method ..... ::getDoctrine();

如何通过 execute() 函数执行此操作?此外,如果有更简单的方法来擦除数据而不是循环遍历它们并删除它们,请随时提及.

How would I do this from the execute() function? Also, if there is an easier way to wipe the data other than to loop through them and remove them, feel free to mention it.

推荐答案

为了能够访问服务容器,您的命令需要扩展 SymfonyBundleFrameworkBundleCommandContainerAwareCommand.

In order to be able to access the service container your command needs to extend SymfonyBundleFrameworkBundleCommandContainerAwareCommand.

参见命令文档章节 - 从容器中获取服务.

See the Command documentation chapter - Getting Services from the Container.

use SymfonyBundleFrameworkBundleCommandContainerAwareCommand;
// ... other use statements

class MyCommand extends ContainerAwareCommand
{
    protected function execute(InputInterface $input, OutputInterface $output)
    {
        $em = $this->getContainer()->get('doctrine')->getEntityManager();
        // ...

相关文章