如何将存储库注入服务

时间:2016-02-04 10:11:30

标签: symfony

我想将一个存储库注入服务中。我的第一步是将存储库定义为服务,如:

<service id="app.repository.user" class="AppBundle\Entity\UserRepository">
        <factory class="doctrine" method="getRepository" />
        <argument>AppBundle:User</argument>
</service>

在第二步中,我注入定义的存储库服务

<service id="app.registration_handler" class="AppBundle\Utils\RegistrationHandler">
        <argument type="service" id="security.password_encoder" />
        <argument type="service" id="app.repository.user" />
    </service>

但我收到此错误消息:

Attempted to load class "doctrine" from the global namespace.
Did you forget a "use" statement?

我记得这在以前的版本中有效,有人有同样的问题和暗示吗?

我正在使用Symfony 3.01

更新: 我解决了我的问题。我错误地定义了一个类而不是一个服务,现在它已经工作了。

<factory service="doctrine" method="getRepository" />

2 个答案:

答案 0 :(得分:1)

自2017年起和Symfony 3.3 + 有很简单的方法可以做到这一点。

查看我的帖子How to use Repository with Doctrine as Service in Symfony 以获得更详细的说明。

对于您的代码 - 您需要做的就是创建自己的存储库作为服务。

1。创建自己的存储库而不直接依赖于Doctrine

<?php

namespace AppBundle\Repository;

use Doctrine\ORM\EntityManagerInterface;

class UserRepository
{
    private $repository;

    public function __construct(EntityManagerInterface $entityManager)
    {
        $this->repository = $entityManager->getRepository(User::class);
    }

    // add desired methods here
    public function findAll()
    {
        return $this->repository->findAll();
    }
}

2。使用PSR-4 based autoregistration

添加配置注册
# app/config/services.yml
services:
    _defaults:
        autowire: true

    AppBundle\:
        resource: ../../src/AppBundle

3。将存储库注入任何服务或控制器现在很容易

<?php

namespace AppBundle\Controller;

use AppBundle\Repository\UserRepository;    

class MyController
{
    /**
     * @var UserRepository
     */
    private $userRepository;

    public function __construct(UserRepository $userRepository)
    {
        $this->userRepository = userRepository
    }
}

答案 1 :(得分:0)

另一个想法是使用"expression language"进入服务配置

<service id="app.registration_handler" class="AppBundle\Utils\RegistrationHandler">
        <argument type="service" id="security.password_encoder" />
        <argument type="expression">service('doctrine').getRepository('AppBundle:User')</argument>
</service>