Symfony-在服务中注入原则存储库 [英] Symfony - inject doctrine repository in service

查看:95
本文介绍了Symfony-在服务中注入原则存储库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

根据如何将存储库注入到服务在Symfony2中? 就像

acme.custom_repository:
    class: Doctrine\ORM\EntityRepository
    factory: ['@doctrine.orm.entity_manager', getRepository]
    arguments:
        - 'Acme\FileBundle\Model\File'

但是我得到一个例外

无效的服务"acme.custom_repository":类 "EntityManager5aa02de170f88_546a8d27f194334ee012bfe64f629947b07e4919__CG __ \ Doctrine \ ORM \ EntityManager" 不存在.

Invalid service "acme.custom_repository": class "EntityManager5aa02de170f88_546a8d27f194334ee012bfe64f629947b07e4919__CG__\Doctrine\ORM\EntityManager" does not exist.

如何在Symfony 3.4中做到这一点?

How can I do this in Symfony 3.4?

EntityClass实际上是一个有效的类FQCN(可以肯定的是,在phpstorm上也使用了复制引用),只是将其重命名,因为其中包含公司名称:).无论如何都更新了它.

EntityClass is actually a valid class FQCN (also used copy reference on phpstorm to be sure) , just renamed it because a companies name is in it :). updated it anyway.

BlueM的解决方案可以完美运行. 如果您不使用自动装配,则以下是服务定义:

BlueM's solution works perfectly. In case you are not using autowiring here's the service defintion:

Acme\AcmeBundle\Respository\MyEntityRepository:
    arguments:
        - '@Doctrine\Common\Persistence\ManagerRegistry'
        - Acme\AcmeBundle\Model\MyEntity # '%my_entity_class_parameter%'

推荐答案

在使用Symfony 3.4时,可以使用更简单的方法,即ServiceEntityRepository.只需实现您的存储库,将其设置为extendServiceEntityRepository,您就可以轻松地注入它. (至少在使用自动装配时-我没有在经典的DI配置中使用过它,但会认为它也应该可以使用.)

As you are using Symfony 3.4, you can use a much simpler approach, using ServiceEntityRepository. Simply implement your repository, let it extend class ServiceEntityRepository and you can simply inject it. (At least when using autowiring – I haven’t used this with classic DI configuration, but would assume it should also work.)

换句话说:

namespace App\Repository;

use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
use Doctrine\Common\Persistence\ManagerRegistry;

class ExampleRepository extends ServiceEntityRepository
{
    /**
     * @param ManagerRegistry $managerRegistry
     */
    public function __construct(ManagerRegistry $managerRegistry)
    {
        parent::__construct($managerRegistry, YourEntity::class);
    }
}

现在,没有任何DI配置,您可以将存储库注入到任意位置,包括控制器方法.

Now, without any DI configuration, you can inject the repository wherever you want, including controller methods.

一个警告(同样适用于您尝试注入存储库的方式):如果重置了Doctrine连接,您将引用一个过时的存储库.但是恕我直言,这是我接受的风险,否则我将无法直接注入存储库.

One caveat (which equally applies to the way you try to inject the repository): if the Doctrine connection is reset, you will have a reference to a stale repository. But IMHO, this is a risk I accept, as otherwise I won’t be able to inject the repository directly..

这篇关于Symfony-在服务中注入原则存储库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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