Symfony2-如何在自定义控制台命令中访问服务? [英] Symfony2 - How to access the service in a custom console command?

查看:73
本文介绍了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();
        // ...

这篇关于Symfony2-如何在自定义控制台命令中访问服务?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆