Symfony2中的依赖注入最佳实践

前端之家收集整理的这篇文章主要介绍了Symfony2中的依赖注入最佳实践前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
在Symfony2(本例中为2.8)中,将服务注入其他服务时,最佳做法是什么?

/**
 * 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中单独设置它们的参数?

我想知道等式的性能部分是什么.

解决方法

两种情况都有利弊.

>在性能方面,两个选项都是相同的,因为只有在请求服务实例时才会获得存储库实例.无论你手动完成,还是由DI自动完成.作为here的精神,

The container is lazy: it doesn’t instantiate a service until (and unless) you ask for it.

>如果您要使用单元测试来覆盖您的服务 – 那么选项2肯定会更好,因为您不需要在测试开始时模拟$em-> getRepository()调用.>个人制定者的好处 – 也与单元测试有关.例如,对于一个测试用例,您只需要一个依赖项,另一个测试用例 – 另一个依赖项.因此,您可以在test中使用setter来设置模拟,而不需要将所有模拟传递给构造函数.

猜你在找的设计模式相关文章