Symfony2中的依赖注入最佳实践
发布时间:2020-12-14 04:48:27 所属栏目:百科 来源:网络整理
导读:在Symfony2(本例中为2.8)中,将服务注入其他服务时,最佳做法是什么? /** * Checker constructor. * @param EntityManager $em * @param EventDispatcherInterface $dispatcher */public function __construct(EntityManager $em,EventDispatcherInterface $d
在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的精神,
>如果您要使用单元测试来覆盖您的服务 – 那么选项2肯定会更好,因为您不需要在测试开始时模拟$em-> getRepository()调用.>个人制定者的好处 – 也与单元测试有关.例如,对于一个测试用例,您只需要一个依赖项,另一个测试用例 – 另一个依赖项.因此,您可以在test中使用setter来设置模拟,而不需要将所有模拟传递给构造函数. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |