我使用的symfony 4,我想访问一个存储库的实体,如果我在指挥类。没有一个功能getDoctrine
或东西..
我已经通过控制台创建的实体,所以我得到了一个实体的存储库。
有谁知道我可以访问存储库?
最好的做法是把这个任务委托给服务。见这个例子:https://symfony.com/doc/current/console.html#getting-services-from-the-service-container
然而,你也可以添加一个构造函数来命令,并给它一个ContainerInterface。然后,你只是做$this->container->get('doctrine')->getManager();
// YourCommand.php
private $container;
public function __construct(ContainerInterface $container)
{
parent::__construct();
$this->container = $container;
}
protected function execute(InputInterface $input, OutputInterface $output)
{
$em = $this->container->get('doctrine')->getManager();
// do stuff...
}
另外,不要忘了在你的脚本的开头添加适当“使用”的语句:
use Symfony\Component\DependencyInjection\ContainerInterface;
使用Symfony的4.2在这里。
use Symfony\Component\Console\Command\Command;
use Doctrine\DBAL\Connection;
class ArchiveCommand extends Command
{
protected static $defaultName = 'simon:test:archive';
private $connection;
public function __construct(Connection $connection)
{
$this->connection = $connection;
parent::__construct();
}
/**
* {@inheritdoc}
*/
protected function execute(InputInterface $input, OutputInterface $output)
{
$this->connection->prepare('SQL HERE');
}
正是作品从容器中得到它,但使用它废弃的从containerAwareInterface和现在应该被注入。
我用这个语法:
$em = $this->getContainer()->get('doctrine')->getEntityManager();