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

问题描述:

我是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.

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

In order to be able to access the service container your command needs to extend Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand.

请参阅命令"文档章节-

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

use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand;
// ... other use statements

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