我应该输入依赖注入变量吗?
假设 Foo 类需要注入 Bar 类。我应该输入提示方法参数,因为我知道 Bar 需要是什么,还是不应该输入提示,以防 Bar 将来发生变化?
class Foo {
public function __construct( Bar $bar ) {
// do something
}
}
或者:
class Foo {
public function __construct( $bar ) {
// do something
// the wrong class could be passed in here, but I'm also future-proof in case
// another class provides similar functionality to Bar
}
}
据推测,“最好”的答案是让 Bar 实现一个接口,但我真的觉得创建一个在可预见的未来只有一个扩展类的接口很愚蠢。最佳实践是什么?
Let's say class Foo requires injection of class Bar. Should I typehint the method parameter because I know what Bar needs to be, or should I not typehint it, in case Bar changes in the future?
class Foo {
public function __construct( Bar $bar ) {
// do something
}
}
or:
class Foo {
public function __construct( $bar ) {
// do something
// the wrong class could be passed in here, but I'm also future-proof in case
// another class provides similar functionality to Bar
}
}
Presumably, the "best" answer is to make Bar implement an interface, but I really feel silly creating an interface that will only have one extension class for the foreseeable future. What is the best practice?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
简单、容易的解决方案:现在将 typehint 键入
Bar
,然后创建一个界面并稍后更改 typehint。如果您正确使用重构实践并良好地设计代码,则更改以后应该不会产生任何影响。The simple, easy solution: typehint to
Bar
for now, and create an interface and change the typehint later. If you use refactoring practices properly and design your code well, the change should have no effect later on.