在Symfony2中(在這種情況下爲2.8)在將服務注入到另一個服務時被認爲是最佳實踐?Symfony2中的依賴注入最佳實踐
/**
* Checker constructor.
* @param EntityManager $em
* @param EventDispatcherInterface $dispatcher
*/
public function __construct(EntityManager $em, EventDispatcherInterface $dispatcher)
{
$this->repoUser = $em->getRepository(User::class);
$this->repoPurchase = $em->getRepository(Purchase::class);
$this->repoTicket = $em->getRepository(Ticket::class);
$this->dispatcher = $dispatcher;
}
或
/**
* Checker constructor.
* @param UserRepository $ur
* @param PurchaseRepository $pr
* @param TicketRepository $tr
* @param EventDispatcherInterface $dispatcher
*/
public function __construct(UserRepository $ur, PurchaseRepository $pr, TicketRepository $tr, EventDispatcherInterface $dispatcher)
{
$this->repoUser = $ur;
$this->repoPurchase = $pr;
$this->repoTicket = $tr;
$this->dispatcher = $dispatcher;
}
,或者使用setter方法明確和services.yml
單獨設置參數呢?
我想知道等式的性能部分是什麼。
你可能**最好是第一個,原因是1)更靈活,如果你以後需要其他存儲庫(或減少一些),因爲你只需要觸摸該類而不是'services.yml'(這個是可辯論的,但**我認爲它更乾淨)2)ServiceContainer只需查找一個引用而不是幾個。 – ccKep