0
我需要在服務中的我的MyEntityRepository
,上調用一些方法。我已經看到了關於注射@doctrine.orm.default_entity_manager
獲取所需資源庫的一些例子:在Symfony 2中編寫可測試的服務並推動使用DiC
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']