当前位置 : 主页 > 手机开发 > 其它 >

Symfony2中的依赖注入最佳实践

来源:互联网 收集:自由互联 发布时间:2021-06-22
在Symfony2(本例中为2.8)中,将服务注入其他服务时,最佳做法是什么? /** * Checker constructor. * @param EntityManager $em * @param EventDispatcherInterface $dispatcher */public function __construct(EntityManager $em, Eve
在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来设置模拟,而不需要将所有模拟传递给构造函数.

网友评论