标签:php dependency-injection interface decoupling
对于依赖注入,我知道我必须将一个类的实例传递给主实例而不是主类创建它自己的实例,就像这样(php):
class Class_One {
protected $_other;
public function setOtherClass( An_Interface $other_class ) {
$this->_other_class = $other_class;
}
public function doWhateverYouHaveToDoWithTheOtherClass() {
$this->_other_class->doYourThing();
}
}
interface An_Interface {
public function doYourThing();
}
class Class_Two implements An_Interface {
public function doYourThing() { }
}
class Class_Three implements An_Interface {
public function doYourThing() { }
}
// Implementation:
$class_one = new Class_One();
$class_two = new Class_Two();
$class_three = new Class_Three();
$class_one->setOtherClass( $class_two );
$class_one->doWhateverYouHaveToDoWithTheOtherClass();
$class_one->setOtherClass( $class_three );
$class_one->doWhateverYouHaveToDoWithTheOtherClass();
这一切都很好.我知道,由于Class_Two和Class_Three都实现了An_Interface,因此它们可以在Class_One中互换使用. Class_One不会知道它们之间的区别.
我的问题是,不是将实例传递给setOtherClass,而是传递一个字符串,如“Class_Two”,并让Class_One的setOtherClass方法实际创建实例本身,这是一个好主意:
class Class_One {
...
public function setOtherClass( $other_class_name ) {
$this->_other_class = new $other_class_name();
}
...
}
这种方式是否会破坏依赖注入的目的,还是完全有效?我认为这种类型的设置可以帮助我进行配置,用户可以在之前的字符串中指定要使用的类,稍后可以将其传递给Class_One.
实际上,写出来让我觉得它可能不是一个好的解决方案,但我仍然会发布这个以防万一有人可以给我一些很好的反馈,说明为什么我应该/不应该这样做.
谢谢=)
瑞安
解决方法:
这在理论上违背了依赖注入的目的;你告诉Class_One,它取决于An_Interface,它应该实例化该接口的具体实现.这要求Class_One知道如何实例化ANY An_Interface实现,将Class_One紧密耦合到所有An_Interface实现.如果你添加一个新的An_Interface Class_Four,你必须返回并告诉Class_One如何实例化Class_Four.
在PHP中,由于所有An_Interface实现都具有无参数构造函数,因此您可以远离这一点.但是,如果任何实现需要注入其他依赖项,那么你就搞砸了;如果Class_Four需要Class_One不知道的Class_Five,你不能告诉Class_One只是新建一个Class_Four.
标签:php,dependency-injection,interface,decoupling 来源: https://codeday.me/bug/20190610/1211633.html
本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。