在Laravel中,使用App :: make('')而不是构造函数注入有什么弊端? [英] In Laravel, any downside to using App::make('') rather than constructor injection?

查看:843
本文介绍了在Laravel中,使用App :: make('')而不是构造函数注入有什么弊端?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

通常,我只是通过构造函数注入依赖关系,但是当父类具有依赖关系并且必须将其传递给所有子代时,它变得非常冗长.

Normally I would just inject dependancies via the constructor, but it gets to be very verbose when the parent class has dependancies and have to pass them through all the children.

替代方法是仅在父类中使用$this->dependancy = App::make('Dependancy').然后,父构造函数和子构造函数都可以为空.这样做有什么弊端吗?

The alternative is to use $this->dependancy = App::make('Dependancy') in the parent class alone. Then both the parent and child constructors can be empty. Is there any downside to doing it this way?

推荐答案

您的方法有一个缺点,按照您的建议进行操作会降低应用程序的可测试性.

There is a downside to your approach, doing what you propose will make your application less testable.

我的意思是,如果您尝试为父类编写单元测试,您将不再孤立地测试该父类.现在,您的测试还取决于父类内部声明的依赖项的结果.

What I mean is that if you try to write a unit test for the parent class you will no longer be testing that parent class in isolation. Your test now also depends on the results from the dependency declared inside the parent class.

如果通过构造函数注入(或任何类型的注入)传递此依赖关系,则可以控制该依赖关系,并且可以模拟/存根该依赖关系的输出,并更好地隔离测试您的父类.

If you pass this dependency in through constructor injection (or any type of injection) you have control over the dependency and can mock/stub the output from it and better test your parent class in isolation.

这篇关于在Laravel中,使用App :: make('')而不是构造函数注入有什么弊端?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆