我需要在服务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']