Symfony 4:指挥学说 [英] Symfony 4: doctrine in command

查看:20
本文介绍了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:指挥学说的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆