Symfony2/JmsDIExtraBundle 使用注释将存储库注入服务

Symfony2/JmsDIExtraBundle Injecting repository into service using annotations

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

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

   ####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);

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

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

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

在标准的 Symfony 服务定义方式中:

   ####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(参见 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;
    }

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

希望对您有所帮助