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 关于#MATLAB#的问题,如何解决?(相关搜索:信噪比,系统容量)
  • ¥500 52810做蓝牙接受端
  • ¥15 基于PLC的三轴机械手程序
  • ¥15 多址通信方式的抗噪声性能和系统容量对比
  • ¥15 winform的chart曲线生成时有凸起
  • ¥15 msix packaging tool打包问题
  • ¥15 finalshell节点的搭建代码和那个端口代码教程
  • ¥15 Centos / PETSc / PETGEM
  • ¥15 centos7.9 IPv6端口telnet和端口监控问题
  • ¥20 完全没有学习过GAN,看了CSDN的一篇文章,里面有代码但是完全不知道如何操作