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;
相关文章