控制台命令中symfony2中的文档管理器

Lal*_*han 3 symfony-2.1

我的symfony网站需要一个cron作业.我在http://symfony.com/doc/2.1/cookbook/console/console_command.html找到了创建控制台命令的教程

我的命令.php

namespace xxx\WebBundle\Command;

使用Symfony\Component\Console\Command\Command; 使用Symfony\Component\Console\Input\InputArgument; 使用Symfony\Component\Console\Input\InputInterface; 使用Symfony\Component\Console\Input\InputOption; 使用Symfony\Component\Console\Output\OutputInterface;

class GreetCommand extends Command {protected function configure(){

}

protected function execute(InputInterface $input, OutputInterface $output)
{

    $em = $this->getContainer()->get('doctrine')->getManager();
    $em->getRepository('xxxWebBundle:Wishlist')->findAll();
   // $output->writeln($text);
} 
Run Code Online (Sandbox Code Playgroud)

}

当我在控制台中调用命令时,收到错误"调用未定义的方法xxxx\WebBundle\Command\MyCommand :: getContainer()"如何在执行函数中获取文档管理器?

Tib*_*Tib 6

您需要扩展ContainerAwareCommand才能访问$this->getContainer()

namespace xxx\WebBundle\Command;

//Don't forget the use
use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;

class GreetCommand extends ContainerAwareCommand { 
  protected function configure() {}

  protected function execute(InputInterface $input, OutputInterface $output)
  {

    $em = $this->getContainer()->get('doctrine')->getManager();
    $em->getRepository('xxxWebBundle:Wishlist')->findAll();
    // $output->writeln($text);
  } 
}
Run Code Online (Sandbox Code Playgroud)