OOP依赖关系:依赖关系注入与注册表 [英] OOP Dependencies: Dependency Injection vs. Registry

查看:95
本文介绍了OOP依赖关系:依赖关系注入与注册表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我了解一些OOP,并且已经读过这篇文章,但是我不是骨灰级的OOP专家,没有经过正式的培训,无法说出为什么某些东西应该使用依赖项注入,并且可能无法识别所有依赖项在设计中,因此是我的问题.

I know some OOP and have read this and that, but am not a hardcore OOP guy and have no formal training and can't rattle off why something should use dependency injection or not, and may not be able to identify all dependencies in a design, hence my question.

在此处回答一个问题(使用对象使用其他对象的方法)我开始怀疑自己.就依赖而言,是更好还是更坏,还是两者都可以接受?有设计上的限制吗?

Answering a question here on SO (Using a object in methods of other objects) I started to doubt myself. As far as dependencies, is one of these better or worse or both acceptable? Any design limitations?

我已经阅读并理解了两者,但从未进行过比较.为什么在设计等中更好地使用它?

I have read and understand both but haven't ever come across a comparison. Why would one be better used in a design, etc.

依赖注入:

class myClass {
    private $db;

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

注册表(也许还有其他):

class myClass {
    private $db;

    public function __construct() {
        $this->db = Registry::get('db');
    }
}

推荐答案

这两种方法都是依赖注入的可能实现.基本上,依赖注入是指定义一种配置(注入)运行时要使用的类的方法,以使其与在代码中使用硬编码的类名和构造函数相比,使代码更灵活.依赖注入遵循称为 inversion of control 的原理.

Both methods are possible implementations of dependency injection. Basically dependency injection means to define a way to configure (inject) the classes to be used at runtime in order to make to code more flexible compared to using using hard coded class names and constructors in the code. Dependency injection follows a principle called inversion of control.

这对于测试代码特别有意思,但可以用于希望使应用程序灵活和可维护的其他各种情况.

This is especially interesting for testing code but can be used in a variety of other scenarios where you want to make an application flexible and maintainable.

虽然依赖注入大多数被称为DI container,但是通常可以使用两种不同的方法来完成它-它们也可以共存.这里有一个(不完整的)列表:

While dependency injection mostly is referred to as DI container, it can generally be done using a couple of different methods - which may also coexist. Here comes an (incomplete) list:

  • 使用依赖项注入容器
  • 通过类依赖作为构造函数或方法args
  • 使用中央注册表(只要它是可配置的)
  • 使用setter方法设置依赖项
  • 使用配置文件
  • 用户输入
  • ...

这篇关于OOP依赖关系:依赖关系注入与注册表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆