Symfony 4:指挥学说

Symfony 4: doctrine in command(Symfony 4:指挥学说)
本文介绍了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:指挥学说的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Convert JSON integers and floats to strings(将JSON整数和浮点数转换为字符串)
in php how do I use preg replace to turn a url into a tinyurl(在php中,如何使用preg替换将URL转换为TinyURL)
all day appointment for ics calendar file wont work(ICS日历文件的全天约会不起作用)
trim function is giving unexpected values php(Trim函数提供了意外的值php)
Basic PDO connection to MySQL(到MySQL的基本PDO连接)
PHP number_format returns 1.00(Php number_Format返回1.00)