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

Mag*_*ity 9 php console command symfony

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

在控制器中我会这样做:

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

$em = $this->getDoctrine()->getManager();
foreach($nodes as $node)
{
    $em->remove($node);
}
$em->flush();
Run Code Online (Sandbox Code Playgroud)

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

Call to undefined method ..... ::getDoctrine();
Run Code Online (Sandbox Code Playgroud)

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

Nic*_*ich 15

为了能够访问服务容器,您的命令需要扩展Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand.

请参阅命令文档一章 - 从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();
        // ...
Run Code Online (Sandbox Code Playgroud)


Tom*_*uba 13

Symfony 3.3(2017年5月)开始,您可以轻松地在命令中使用依赖注入.

只需在您的:中使用PSR-4服务自动发现services.yml:

services:
    _defaults:
        autowire: true

    App\Command\:
        resource: ../Command
Run Code Online (Sandbox Code Playgroud)

然后使用常见的构造函数注入,最后甚至Commands将具有干净的架构:

final class MyCommand extends Command
{
    /**
     * @var SomeDependency
     */
    private $someDependency;

    public function __construct(SomeDependency $someDependency)
    {
        $this->someDependency = $someDependency;

        // this is required due to parent constructor, which sets up name 
        parent::__construct(); 
    }
}
Run Code Online (Sandbox Code Playgroud)

Symfony 3.4(2017年11月)以来,这将(或已经确实,取决于时间阅读)成为标准,当命令将被延迟加载时.