Symfony 4:命令学说 [英] Symfony 4: doctrine in command

查看:54
本文介绍了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...
}

也,不要忘记在脚本开始时添加正确的 use语句:

Also, don't forget to add the proper "use" statement at the beggining of your script:

use Symfony\Component\DependencyInjection\ContainerInterface;

这篇关于Symfony 4:命令学说的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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