0

我需要在服务MyEntityRepository中调用我的一些方法。我已经看到了一些关于注入以获取所需存储库的示例:@doctrine.orm.default_entity_manager

namespace Acme\HelloBundle\Service;     

use Doctrine\ORM\EntityManager;

Class MyService
{
    private $entityManager;

    public function __construct(EntityManager $entityManager)
    {
        $this->entityManager = $entityManager;
    }

    public function doStuff()
    {
        $repo = $this->entityManager->getRepository('AcmeHelloBundle:MyEntity');

        // Do stuff
    }
}

使用此服务定义:

my_service:
  class: Acme\HelloBundle\Service\MyService
  arguments: ['@doctrine.orm.default_entity_manager']

问题是此代码可测试吗?为了将来的测试目的而注入会更好MyEntityRepository(使用模拟对象作为存储库)?

namespace Acme\HelloBundle\Service;

use Acme\HelloBundle\Repository\MyEntityRepository;

Class MyService
{
    private $er;

    public function __construct(MyEntityRepository $er) { $this->er = $er; }

    public function doStuff()
    {
        $repo = $this->er;

        // Do stuff
    }
}

使用:

my_entity_repository:
  class: Acme\HelloBundle\Repository\MyEntityRepository
  factory_service: doctrine.orm.default_entity_manager
  factory_method: getRepository
  arguments: ['Acme\HelloBundle\Entity\MyEntity']

my_service:
  class: Acme\HelloBundle\Service\MyService
  arguments: ['@my_entity_repository']
4

1 回答 1

0

我认为实体存储库比实体管理器更容易模拟,因为您必须模拟 getRepository 才能返回实体存储库模拟,因此在这两种情况下,您都必须创建一个实体存储库模拟。

但这并不是我认为第二种解决方案更好的唯一原因:您的依赖关系通过这种方式更加清晰,可以看到您的类真正需要什么(实体管理器其他方法未使用)。

使用第二种解决方案会使对象的创建更加复杂,但这是 DIC 可以解决的问题。

于 2012-05-30T22:09:41.750 回答