创建symfony命令扩展控制器

时间:2019-08-19 10:55:03

标签: php shell symfony

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

在MyCommand类中,我需要使用getDoctrine-function,因此我必须扩展控制器,但是我看不到一种方法。有什么想法吗?

当前,我在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();
    }
  }
?>

1 个答案:

答案 0 :(得分:2)

getDoctrine()提供了ControllerTrait方法,而容器注入取决于ContainerAwareTrait。但是,这将提取命令中不需要的其他服务和方法,因此建议不要注入整个容器,而只是注入所需的服务,在这种情况下,该服务就是ObjectManagerObjectManager是由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(/*...*/);
    }
  }