在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