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

查看:18
本文介绍了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.

推荐答案

为了能够访问服务容器,您的命令需要扩展 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();
        // ...

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

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