如何EntityManager
从Symfony 3中的命令访问?应该是ContainerAware
。
这是我的代码:
use Symfony\Component\Console\Command\Command;
class MyCommand extends Command
{
protected function execute(InputInterface $input, OutputInterface $output)
{
$em = $this->getContainer()->getDoctrine();
...
}
}
我得到这个错误:
未捕获的Symfony \ Component \ Debug \ Exception \ UndefinedMethodException:试图调用类“ AppBundle \ Command \ MyCommand”的名为“ getContainer”的未定义方法
如果我从Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand
(symfony 2方式)扩展,也会发生这种情况。
此外,注射Doctrine\ORM\EntityManager
在__construct()
没有工作。
您不能使用getContainer,因为您的命令类无法识别该容器。
使您的命令扩展ContainerAwareCommand
这样就可以使用getContainer()
use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand;
然后扩展ContainerAwareCommand:
class MyCommand extends ContainerAwareCommand
然后在任何需要的地方使用它:
$em = $this->getContainer()->get('doctrine')->getManager('default');
编辑感谢@ tomas-votruba:
但是,Symfony 4中不推荐使用ContainerAware :
通过注入使用EntityManager:
因此,与其强行使用容器来获取实体管理器,不如注入您的构造函数,并通过将命令用作服务来扩展Command :
namespace App\Command;
use Doctrine\Common\Persistence\ObjectManager;
use Symfony\Component\Console\Command\Command;
class MyCommand extends Command {
//add $entityManager attribute
private $entityManager;
public function __construct(ObjectManager $entityManager)
{
$this->entityManager= $entityManager;
// you *must* call the parent constructor
parent::__construct();
}
如您在构造函数中看到的那样,我们向ObjectManager注入了ObjectManager,ObjectManager是一个接口,而EntityManager是其ORM实现,如果您使用默认的services.yml或为自动装配设置的服务,则可以这样做:
# config/services.yaml
services:
# default configuration for services in *this* file
_defaults:
autowire: true # Automatically injects dependencies in your services.
autoconfigure: true # Automatically registers your services as commands, event subscribers, etc.
public: false # Allows optimizing the container by removing unused services; this also means
# fetching services directly from the container via $container->get() won't work.
# The best practice is to be explicit about your dependencies anyway.
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句