首页 > 解决方案 > 创建 symfony 命令扩展控制器

问题描述

我正在编写一个 symfony 控制台命令,它可以通过使用“php bin/console app:mycommand”(symfony 文档:https ://symfony.com/doc/current/console.html#creating-a-command )来执行。

在我的 MyCommand 类中,我需要使用 getDoctrine 函数,所以我必须扩展控制器,但我看不到如何做到这一点。有任何想法吗?

目前我在 CLI 上收到以下错误:尝试调用类“App\Command\MyCommand”的名为“getDoctrine”的未定义方法。

<?php
  // src/Command/MyCommand.php
  namespace App\Command;

  use Symfony\Component\Console\Command\Command;
  use Symfony\Component\Console\Input\InputInterface;
  use Symfony\Component\Console\Output\OutputInterface;

  use Symfony\Bundle\FrameworkBundle\Controller\Controller;

  class MyCommand extends Command
  {
    // the name of the command (the part after "bin/console")
    protected static $defaultName = 'app:mycommand';

    protected function configure()
    {

    }

    protected function execute(InputInterface $input, OutputInterface $output)
    {
      // Not working, producing mentioned error 
      $em = $this->getDoctrine()->getManager();
    }
  }
?>

标签: phpshellsymfony

解决方案


getDoctrine()方法由 提供ControllerTrait,而后者又取决于ContainerAwareTrait容器注入的 。但是,这将提取您在命令中不需要的其他服务和方法,因此建议的方法是只注入您需要的服务,而不是注入整个容器,在这种情况下是ObjectManager(ObjectManager是实现的通用接口都由 ORM 和 ODM,如果你同时使用或者你只关心 ORM,你可以使用Doctrine\ORM\EntityManagerInterface)。

  <?php
  // src/Command/MyCommand.php
  namespace App\Command;

  use Symfony\Component\Console\Command\Command;
  use Symfony\Component\Console\Input\InputInterface;
  use Symfony\Component\Console\Output\OutputInterface;

  use Doctrine\Common\Persistence\ObjectManager;

  class MyCommand extends Command
  {
    // the name of the command (the part after "bin/console")
    protected static $defaultName = 'app:mycommand';

    private $manager;

    public function __construct(ObjectManager $manager)
    {
        $this->manager = $manager;
        parent::__construct();
    }

    protected function execute(InputInterface $input, OutputInterface $output)
    {
        // Now you have access to the manager methods in $this->manager
        $repository = $this->manager->getRepository(/*...*/);
    }
  }

推荐阅读