Symfony 4: doctrine in command(Symfony 4:指挥学说)
问题描述
我正在使用 symfony 4,如果我在 Command 类中,我想访问实体的存储库.没有函数 getDoctrine 什么的..
I am using symfony 4 and I want to access a repository for an entity if I am in the Command class. There is not a function getDoctrine or something..
我已经通过控制台创建了一个实体,所以我得到了一个实体和一个存储库.
I have created an Entity through the console, so I got an entity and a repository.
有人知道我如何访问存储库吗?
Does anybody know how I can access the repository?
推荐答案
最佳实践是将此任务委托给服务.请参阅此示例:https://symfony.com/doc/current/console.html#getting-services-from-the-service-container
The best practice is to delegate this task to a service. See this example: https://symfony.com/doc/current/console.html#getting-services-from-the-service-container
但是,您也可以向命令添加构造函数并为其提供 ContainerInterface.然后你只需执行 $this->container->get('doctrine')->getManager();
However you can also add a constructor to the command and give it a ContainerInterface. Then you just do $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...
}
另外,不要忘记在脚本开头添加正确的使用"语句:
Also, don't forget to add the proper "use" statement at the beggining of your script:
use SymfonyComponentDependencyInjectionContainerInterface;
这篇关于Symfony 4:指挥学说的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Symfony 4:指挥学说
基础教程推荐
- 有什么方法可以用编码 UTF-8 而不是 Unicode 返回 PHP`json_encode`? 2021-01-01
- PHP PDO MySQL 查询 LIKE ->多个关键词 2021-01-01
- 如何在 Laravel 中使用 React Router? 2022-01-01
- 如何在 Laravel 5.3 注册中添加动态下拉列表列? 2021-01-01
- 学说 dbal querybuilder 作为准备好的语句 2022-01-01
- PHP 类:全局变量作为类中的属性 2021-01-01
- 如何替换eregi() 2022-01-01
- Cron Jobs 调用带有变量的 PHP 脚本 2022-01-01
- 在PHP中根据W3C规范Unicode 2022-01-01
- YouTube API v3 点赞视频,但计数器不增加 2022-01-01
