Symfony2/JmsDIExtraBundle 使用注解将存储库注入服务 [英] Symfony2/JmsDIExtraBundle Injecting repository into service using annotations

查看:21
本文介绍了Symfony2/JmsDIExtraBundle 使用注解将存储库注入服务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的项目中,我将注释与 JMSDIExtraBundle 一起使用.我的问题是:我如何告诉我的应用程序存储库应该是服务,所以我可以使用注释将它注入另一个服务中.我知道的唯一方法是使用 XML 文件将存储库定义为服务.但这是一个非常缓慢的过程(与简单的 @DI\Service 相比,我更喜欢在 yml 或 xml 文件中定义它).

In my project I’m using annotations with JMSDIExtraBundle. My question is: how I can tell my app that repository should be service so, I can inject it in another service using annotations. Only way I know is using XML file to define repository as service. But it’s a very slow process(comparing it to simple @DI\Service which I prefer over defining it in yml or xml files).

我找到了 XML 的替代解决方案,但我认为这是个坏主意:

I found an alternative solution to XML but I think it's bad idea:

   ####CustomService.php####
   /**
     * @param EntityManager $em
     *
     * @DI\InjectParams({
     *     "em" = @DI\Inject("doctrine.orm.entity_manager")
     * })
     */
    public function __construct(EntityManager $em) {
        $this->em = $em;
    }

在某处服务:

$entityRepository = $this->em->getRepository(AcmeBundle:Entity);

有什么想法可以在我需要使用存储库时加快编码过程吗?

Any ideas how I can speed up coding process when I need to use repository?

推荐答案

您可以将实体存储库定义为服务并将其注入到服务中.

You can define your entity repository as a service and inject it into the service.

例如,您可以将存储库配置为如下服务:

As Example, you can configure the repo as a service like:

以标准的 Symfony 服务定义方式:

In a standard Symfony Service definition Way:

   ####service.xml####
    <service id="acme.user.repository"
             class="Doctrine\ORM\EntityRepository"
             factory-service="doctrine.orm.entity_manager"
             factory-method="getRepository">
        <argument>AcmeDemoBundle:User</argument>
    </service>

或者使用 JMSDiExtraBundle 中定义的 factory to Service annotation(参见 ):

Or using the factory to Service annotation defined in the JMSDiExtraBundle (see this):

/**
 * @Service("acme.user.repository", factoryService = "doctrine", factoryMethod="getRepository", factoryMethodArguments={
 * "persistentObjectName" = "Acme\DemoBundle\Entity\User"
 * } )
*/

并注入并将其用作:

   ####CustomService.php####
   /**
     * @param Doctrine\ORM\EntityRepository $repo
     *
     * @DI\InjectParams({
     *     "repo" = @DI\Inject("acme.user.repository")
     * })
     */
    public function __construct(EntityRepository $repo) {
        $this->repo = $repo;
    }

不是一个很好的加速,但允许只注入你需要的东西

Is not a great speedup, but permit to only inject what you need

希望对您有帮助

这篇关于Symfony2/JmsDIExtraBundle 使用注解将存储库注入服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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