duanbogan5878 2016-04-26 19:24
浏览 305

PHP - 如果自动加载,为什么要使用依赖注入?

Please forgive the possible naivety of this question, however I am getting myself really confused. It appears that it is good practice to use dependancy injection to decouple your code so that your classes are loaded with their dependancies. PLease imagine the following where Class Foo has a dependancy of class Bar

namespace Classes;

class Foo{

    protected barInstance;

    public function __construct(Bar $barInstance){
        $this->barInstance=$barInstance;
    }

}

However if you are autoloading your classes then surely the following does the exact same thing without the need of DI?

namespace Classes;
use Classes/Bar;

class Foo{

    protected barInstance;

    public function __construct(){
        $this->barInstance=new Bar;
    }

}

Thanks to any responders.

  • 写回答

4条回答 默认 最新

  • donglu5000 2016-04-26 19:34
    关注

    These are two separate concepts. Autoloading will allow you to not have to include files in your scripts and allow you to separate your classes by concept. As far as dependency injection, if Bar had additional dependencies and could not simply be instantiated by using new Bar(), but rather new Bar($dep1, $dep2), then your logic to create Bar would be buried inside Foo's constructor, as well as the constructor of any other class which requires Bar. By inverting the dependency creating Bar somewhere else before injecting it, you're relieving Foo of that additional responsibility.

    评论

报告相同问题?