我认为您不应该直接在构造函数中检索容器。相反,请在方法或方法中检索它。在我的情况下,我在这样的方法开始时得到了我的实体经理,一切都很好(用Symfony 2.1测试)。configure
execute
execute
protected function execute(InputInterface $input, OutputInterface $output)
{
$entityManager = $this->getContainer()->get('doctrine')->getEntityManager();
// Code here
}
我认为当您调用构造函数时,应用程序对象的实例化尚未完成,这会导致此错误。该错误来自轮胎要做的方法:getContainer
getContainer
$this->container = $this->getApplication()->getKernel()->getContainer();
由于 还不是对象,因此您会收到一个错误,指出或正在对非对象调用方法。getApplication
getKernel
更新:在较新版本的Symfony中,已被弃用(现在可能已经完全删除)。请改用。感谢肖瑟指出它。getEntityManager
$entityManager = $this->getContainer()->get('doctrine')->getManager();
更新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();
}
}
感谢@profm2提供注释和代码示例。