0

service 内のMyEntityRepositorymyでいくつかのメソッドを呼び出す必要があります。必要なリポジトリを取得するために注入する例を見てきました。@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をモックする必要があるため、エンティティリポジトリのモックはエンティティマネージャよりも簡単だと思います。どちらの場合も、エンティティリポジトリのモックを作成する必要があります。

しかし、これが私の意見で2番目のソリューションが優れている唯一の理由ではありません。この方法で依存関係がはるかに明確になり、クラスが実際に何を必要としているかを確認できます(エンティティマネージャーの他のメソッドは使用されません)。

2番目のソリューションを使用すると、オブジェクトの作成がより複雑になりますが、これはDICが解決できる問題です。

于 2012-05-30T22:09:41.750 に答える