本文介绍了有没有办法将 EntityManager 注入服务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在使用 Symfony 3.3 时,我声明了这样的服务:

While using Symfony 3.3, I am declaring a service like this:

class TheService implements ContainerAwareInterface
{
    use ContainerAwareTrait;
    ...
}

在我需要 EntityManager 的每个操作中,我从容器中获取它:

Inside each action where I need the EntityManager, I get it from the container:

$em = $this->container->get('doctrine.orm.entity_manager');

这有点烦人,所以我很好奇 Symfony 是否有类似 EntityManagerAwareInterface 的东西.

This is a bit annoying, so I'm curious whether Symfony has something that acts like EntityManagerAwareInterface.

推荐答案

传统上,您会在 services.yml 文件中创建新的服务定义,将实体管理器设置为构造函数的参数

Traditionally, you would have created a new service definition in your services.yml file set the entity manager as argument to your constructor

app.the_service:
    class: AppBundle\Services\TheService
    arguments: ['@doctrine.orm.entity_manager']

最近,随着 symfony 3.3 的发布,默认的 symfony-standard-edition 将其默认的 services.yml 文件更改为默认使用 autowire 并添加所有类在 AppBundle 中成为服务.这消除了添加自定义服务的需要,并且在构造函数中使用类型提示将自动注入正确的服务.

More recently, with the release of symfony 3.3, the default symfony-standard-edition changed their default services.yml file to default to using autowire and add all classes in the AppBundle to be services. This removes the need for adding the custom service and using a type hint in your constructor will automatically inject the right service.

您的服务类将如下所示

use Doctrine\ORM\EntityManagerInterface

class TheService
{
    private $em;

    public function __construct(EntityManagerInterface $em)
    {
        $this->em = $em;
    }

    // ...
}

有关自动定义服务依赖项的更多信息,请参阅https://symfony.com/doc/current/service_container/autowiring.html

For more information about automatically defining service dependencies, see https://symfony.com/doc/current/service_container/autowiring.html

新的默认 services.yml 配置文件可在此处获得:https://github.com/symfony/symfony-standard/blob/3.3/app/config/services.yml

The new default services.yml configuration file is available here: https://github.com/symfony/symfony-standard/blob/3.3/app/config/services.yml

这篇关于有没有办法将 EntityManager 注入服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

05-27 05:48
查看更多