dsa45664 2019-08-10 16:01
浏览 141
已采纳

在类方法中使用框架定义的全局常量是否会破坏依赖注入原则?

I have a question regarding OOP with Dependecy Injection.

For example, have constants coming from the framework you are using. i.e, ABSPATH in WordPress

How badly will it break the Dependency Injection principle if I do not add the value of that constant as a dependency in constructor function of the class, and just use it directly inside method?

Say, strictly DI speaking, you need to do something like:

class Foo {

    private $abspath;

    public function __construct(string $abspath) {
         $this->abspath = $abspath
    }

    public function get_assets_dir() {
        return $this->abspath . '/assets/';
    }

}

$foo = new Foo(ABSPATH);
$foo->get_assets_dir();

but instead something like?

class Foo {

    public function __construct() {
         //nothing here.
    }

    public function get_assets_dir() {
        return ABSPATH . '/assets/';
    }

}

Do I really still have to do it if it will always be defined since it sits on top of a framework that defines it by default?

  • 写回答

1条回答 默认 最新

  • dpb56083 2019-08-10 16:25
    关注

    Strictly speaking, yes. (Although it's called the "Dependency Inversion Principle", not "Dependency Injection" principle. The "Dependency Injection Pattern" it's a subpattern of the "Inversion of Control" principle; related but not the same. Read more about this here.

    ABSPATH is dependency for your Foo class, it is defined outside by different part of the application. If your class needs that value, and aims to be completely decoupled from the "framework", you should inject it (disregarding that the constant belongs to the global state, if you are really encapsulating your class, it doesn't need to be aware of that).

    Realistically, if your class is solely for use in Wordpress (and it looks that way), I wouldn't worry too much. You are already coupled to your "framework" anyway.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog
  • ¥15 Excel发现不可读取的内容
  • ¥15 关于#stm32#的问题:CANOpen的PDO同步传输问题
  • ¥20 yolov5自定义Prune报错,如何解决?