开发者

Should I typehint my dependency injection variables?

开发者 https://www.devze.com 2023-01-30 23:40 出处:网络
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?

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 inte开发者_如何学运维rface, but I really feel silly creating an interface that will only have one extension class for the foreseeable future. What is the best practice?


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号