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

Fes*_*ter 42 php console symfony

我想要一些终端命令到我的Symfony2应用程序.我已经阅读了食谱中示例,但我无法在这里找到如何访问我的设置,我的实体经理和我的实体.在构造函数中,我使用容器(应该让我访问设置和实体)

$this->container = $this->getContainer();
Run Code Online (Sandbox Code Playgroud)

但是这个调用产生了一个错误:

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

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

$this->getApplication()
Run Code Online (Sandbox Code Playgroud)

返回NULL而不是预期的对象.我想我离开了一些重要的一步,但哪一个?我怎样才能最终能够使用我的设置和实体?

Mat*_*att 75

我认为你不应该直接在构造函数中检索容器.而是在configure方法或execute方法中检索它.就我而言,我只是在这个execute方法的开头就得到了我的实体管理器,一切都运行正常(用Symfony 2.1测试).

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

    // Code here
}
Run Code Online (Sandbox Code Playgroud)

我认为当您getContainer在构造函数中调用导致此错误时,应用程序对象的实例化尚未完成.该错误来自getContainer方法tyring:

$this->container = $this->getApplication()->getKernel()->getContainer();
Run Code Online (Sandbox Code Playgroud)

由于getApplication还不是对象,因此您会收到错误说明或正在getKernel非对象上调用方法.

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

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

__constructor使用EntityManagerInterface变量创建一个.可以在其余命令中访问此变量.这遵循自动布线依赖注入方案.

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();
  }
}
Run Code Online (Sandbox Code Playgroud)

致@promm2提供评论和代码示例.

  • 使用最新版本 - > getEntityManager(); 现在已弃用 - > getManager(); (10认同)

stl*_*loc 10

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

class YourCmdCommand extends ContainerAwareCommand
Run Code Online (Sandbox Code Playgroud)

并得到像这样的实体经理:

$em = $this->getContainer()->get('doctrine.orm.entity_manager');
Run Code Online (Sandbox Code Playgroud)