如何在 Symfony 2 控制台命令中使用我的实体和实体管理器?

2022-08-30 11:50:11

我想对我的Symfony2应用程序使用一些终端命令。我已经浏览了说明书中的示例,但我无法在此处找到如何访问我的设置,我的实体管理器和我的实体。在构造函数中,我使用容器(这应该允许我访问设置和实体)

$this->container = $this->getContainer();

但此调用会生成一个错误:

致命错误:在 /Users/fester/Sites/thinkblue/admintool/vendor/symfony/src/Symfony/Bundle/FrameworkBundle/Command/ContainerAwareCommand.php 第 38 行中的非对象上调用成员函数 getKernel()

基本上,在 ContainerAwareCommand->getContainer() 中,调用

$this->getApplication()

返回 NULL,而不是按预期返回的对象。我想我遗漏了一些重要的步骤,但是哪一个呢?我最终将如何能够使用我的设置和实体?


答案 1

我认为您不应该直接在构造函数中检索容器。相反,请在方法或方法中检索它。在我的情况下,我在这样的方法开始时得到了我的实体经理,一切都很好(用Symfony 2.1测试)。configureexecuteexecute

protected function execute(InputInterface $input, OutputInterface $output)
{
    $entityManager = $this->getContainer()->get('doctrine')->getEntityManager();

    // Code here
}

我认为当您调用构造函数时,应用程序对象的实例化尚未完成,这会导致此错误。该错误来自轮胎要做的方法:getContainergetContainer

$this->container = $this->getApplication()->getKernel()->getContainer();

由于 还不是对象,因此您会收到一个错误,指出或正在对非对象调用方法。getApplicationgetKernel

更新:在较新版本的Symfony中,已被弃用(现在可能已经完全删除)。请改用。感谢肖瑟指出它。getEntityManager$entityManager = $this->getContainer()->get('doctrine')->getManager();

更新2:在Symfony 4中,可以使用自动布线来减少所需的代码量。

使用变量创建 。此变量将在其余命令中可访问。这遵循自动连接依赖关系注入方案。__constructorEntityManagerInterface

class UserCommand extends ContainerAwareCommand { 
  private $em; 

  public function __construct(?string $name = null, EntityManagerInterface $em) { 
    parent::__construct($name); 

    $this->em = $em;
  } 

  protected function configure() { 
    **name, desc, help code here** 
  }

  protected function execute(InputInterface $input, OutputInterface $output) { 
    $this->em->getRepository('App:Table')->findAll();
  }
}

感谢@profm2提供注释和代码示例。


答案 2

从 ContainerAwareCommand 而不是 Command 扩展您的命令类

class YourCmdCommand extends ContainerAwareCommand

并得到这样的实体管理器:

$em = $this->getContainer()->get('doctrine.orm.entity_manager');

推荐