依赖注入(Dependency Injection),也成为控制反转(Inversion of Control),一种设计模式,其目的是解除类之间的依赖关系。

假设我们需要举办一个Party,Party需要主持人、厨师、灯光、音响、食品、酒水等等。那么Party对他们存在依赖关系。用程序语言表示如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
//Party.php
class Party{
//主持人
private $_host;
 
function __construct(){
include "./Host.php";
$this->_host = new Host();
}
 
function startParty(){
$this->_host->sayHello();
}
}
 
//Host.php
class Host{
private $_name;
function sayHello(){
echo "My name is " . $this->_name;
}
}
 
//main
$party = new Party();
$party->startParty();

可见Party的运行依赖于Host,没有Host,Party不能单独运行,也不能单独发布为组件。为了解除Party对Host的依赖,我们可以这么做:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
//Party.php
class Party{
//主持人
private $_host;
 
function __construct($host = ""){
if($host){
$this->_host = $host;
}
}
 
function startParty(){
$this->_host->sayHello();
}
 
function setHost($host){
$this->_host = $host;
}
}
 
//Host.php
class Host{
private $_name;
function sayHello(){
echo "My name is " . $this->_name;
}
}
 
//main
$host = new Host();
$party = new Party();
$party->setHost($host);//或者 $party = new Party($host)
$party->startParty();

此时Party类对Host类的依赖被移到外面,运行时Host类通过构造函数或者setter注入到Party中。Party本身可以被单独发 布。如果Host没有sayHello方法,将其注入到Party中必然导致异常。为了约束Host必须含有sayHello方法,可以使用接口。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
//Party.php
class Party{
//主持人
private $_hostInterface;
 
function __construct($host = ""){
if($host){
$this->_hostInterface = $host;
}
}
 
function startParty(){
$this->_hostInterface->sayHello();
}
 
function setHost($host){
$this->_hostInterface = $host;
}
}
 
//HostInterface.php
Interface HostInterface{
public function sayHello();
}
 
//Host.php
class Host implement HostInterface{
private $_name;
function sayHello(){
echo "My name is " . $this->_name;
}
}
 
//main
$host = new Host();
$party = new Party();
$party->setHost($host);//或者 $party = new Party($host)
$party->startParty();

这么做实际上已经达到了解耦的目的,那么下面我要把Party所有依赖的厨师、灯光、音响、食品、酒水都加进去,会是怎样?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
//Party.php
class Party{
//主持人
private $_host;
private $_cooker;
private $_wine;
private $_food;
private $_music;
private $_light;
 
function __construct(){
}
 
function startParty(){
$this->_host->sayHello();
}
 
function setHost($host){
$this->_host = $host;
}
 
function setCooker($cooker){
$this->_cooker = $cooker;
}
 
function set Wine($wine){
$this->_wine = $wine;
}
 
//...等等 food, light, music
}
 
]
//Host.php
class Host{
private $_name;
function sayHello(){
echo "My name is " . $this->_name;
}
}
//Cooker.php
class Cooker{}
class Wine{}
clsas Light{}
//...等等其他类
 
//main
$host = new Host();
$cooker = new Cooker();
$wine = new Wine();
//...等等
$party = new Party();
$party->setHost($host);
$party->setCooker($cooker);
$party->setWine($wine);
$party->setFood($food);
$part->setMusic($music);
$part->setLight($light);
$party->startParty();

代码中大量的实例化和setter调用,是否可以优化?我们需要一个DI容器,在DI中管理各个类,由DI负责注入。此时的DI更像是一个“大工厂模式”。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
//Party.php
class Party{
private $_di;
 
function __construct(){
}
 
function startParty(){
$this->_di->get("Host")->sayHello();
$this->_di->get("Cooker")->cook();
//...
}
 
function setDI($di){
$this->_di = $di;
}
}
 
//HostInterface.php
Interface HostInterface{
public function sayHello();
}
 
//Host.php
class Host implement HostInterface{
private $_name;
function sayHello(){
echo "My name is " . $this->_name;
}
}
 
//main
$di = new DI();
//匿名函数形式
$di->set("Host", function(){
return new Host();
});
//类名
$di->set("Cooker", "Path\To\Cooker.php");
//直接返回实例
$di->set("Wine", new Path\To\Wine.php);
//数组
$di->set("Light", array("className" => "Path\To\Light"));
 
$party = new Party();
$party->setDI($di);
$party->startParty();

DI使用set来注册服务类,注册的方式可以有很多种,他们都是惰性实例化,set时并不实例化,在get时才会实例化。而DI在注册服务类时通常会使用配置来实现,如JSON、XML或者PHP数组。

DI非常注重约定,$di->get(“Host”)获取的实例如果不是Host实例的话,将会引发异常。因此,DI属于强约定模式,通常用 于底层架构,Zend framework 2的核心部分使用DI模式,但在框架应用层使用服务定位模式(ServiceLocator),服务定位模式与依赖注入非常相似,都能够解除类之间的依赖 关系,且实现思路与DI基本一致。

参考资料:
理解PHP 依赖注入
话说 依赖注入(DI) or 控制反转(IoC)
用PHP实现简单的控制反转(IOC) 依赖注入(DI),用JSON配置文件

本文是作者的团队博客ComingX上 理解依赖注入 for Zend framework 2 文章的一份拷贝,同为原创文章。

理解依赖注入 for Zend framework 2的更多相关文章

  1. 深度理解依赖注入(Dependence Injection)

    前面的话:提到依赖注入,大家都会想到老马那篇经典的文章.其实,本文就是相当于对那篇文章的解读.所以,如果您对原文已经有了非常深刻的理解,完全不需要再看此文:但是,如果您和笔者一样,以前曾经看过,似乎看 ...

  2. 【转】理解依赖注入(IOC)和学习Unity

    IOC:英文全称:Inversion of Control,中文名称:控制反转,它还有个名字叫依赖注入(Dependency Injection).作用:将各层的对象以松耦合的方式组织在一起,解耦,各 ...

  3. [转]深度理解依赖注入(Dependence Injection)

    http://www.cnblogs.com/xingyukun/archive/2007/10/20/931331.html 前面的话:提到依赖注入,大家都会想到老马那篇经典的文章.其实,本文就是相 ...

  4. 理解依赖注入(IOC)和学习Unity

    资料1: IOC:英文全称:Inversion of Control,中文名称:控制反转,它还有个名字叫依赖注入(Dependency Injection). 作用:将各层的对象以松耦合的方式组织在一 ...

  5. 学习Unity -- 理解依赖注入(IOC)三种方式依赖注入

    IOC:英文全称:Inversion of Control,中文名称:控制反转,它还有个名字叫依赖注入(Dependency Injection).作用:将各层的对象以松耦合的方式组织在一起,解耦,各 ...

  6. [PHP-DI] 理解依赖注入

    理解依赖注入 依赖注入 和 依赖注入容器 是不同的: 依赖注入 (Dependency injection) 是编写更好代码的一种方法 容器 (Container) 是帮助注入依赖关系的工具 你不需要 ...

  7. 理解依赖注入(Dependency Injection)

    理解依赖注入 Yii2.0 使用了依赖注入的思想.正是使用这种模式,使得Yii2异常灵活和强大.千万不要以为这是很玄乎的东西,看完下面的两个例子就懂了. class SessionStorage { ...

  8. 理解依赖注入(DI - Dependency Injection)

    系列教程 Spring 框架介绍 Spring 框架模块 Spring开发环境搭建(Eclipse) 创建一个简单的Spring应用 Spring 控制反转容器(Inversion of Contro ...

  9. 深入浅出理解依赖注入这种由外部负责其依赖需求的行为,我们可以称其为 “控制反转(IoC)”

    原文地址: http://www.insp.top/learn-laravel-container ,转载务必保留来源,谢谢了! 这个组件现在可以很简单的获取到它所需要的服务,服务采用延迟加载的方式, ...

随机推荐

  1. 装饰者模式及php实现

    装饰模式(Decorator Pattern) : 动态地给一个对象增加一些额外的职责(Responsibility),就增加对象功能来说,装饰模式比生成子类实现更为灵活.其别名也可以称为包装器(Wr ...

  2. Android RecyclerView使用GridLayoutManager间距设置

    使用RecyclerView设置间距,需要重写RecyclerView.ItemDecoration这个类.有如下的效果图需要实现,间距只有中间的格子和底部的格式之间有.   Paste_Image. ...

  3. ImageLoader常用方法注释

    ImageLoader中的常用方法及相关作用注释 ImageLoader 的ImageLoaderConfiguration config 配置 ImageLoaderConfiguration co ...

  4. pytest+allure2+jenkins环境部署

    1.pycharm安装allure-pytest 2.jenkins -> 系统管理 -> 插件管理 -> 可选插件中过滤Allure,勾选对应插件安装 如下图:  3.安装完插件后 ...

  5. Linux下使用crontab命令配置定时任务

    一.语法结构 crontab [-e [UserName]|-l [UserName]|-r [UserName]|-v [UserName]|File ] 说明 : crontab 是用来让使用者在 ...

  6. C++string类型转换为C数组

    #include <string> #include <iostream> using namespace std; int main(){ string str; str.a ...

  7. iOS 学习随记 (一)

    入行IT也已经很多年了,厌倦了Windows平台的工作, 4月初突然抽风买了台Mac就开始决定转身做iOS/OS X下的App开发了. 从适应Mac机器到开始编程没有花费太长时间,也因为有C#和Jav ...

  8. UVA 11987 Almost Union-Find (单点修改的并查集)

    此题最难处理的操作就是将一个单点改变集合,而普通的并查集是不支持这种操作的. 当结点p是叶子结点的时候,直接pa[p] = root(q)是可以的, p没有子结点,这个操作对其它结点不会造成任何影响, ...

  9. [论文理解]SSD:Single Shot MultiBox Detector

    SSD:Single Shot MultiBox Detector Intro SSD是一套one-stage算法实现目标检测的框架,速度很快,在当时速度超过了yolo,精度也可以达到two-stag ...

  10. Hbase 完全分布式 高可用 集群搭建

    1.准备 Hadoop 版本:2.7.7 ZooKeeper 版本:3.4.14 Hbase 版本:2.0.5 四台主机: s0, s1, s2, s3 搭建目标如下: HMaster:s0,s1(备 ...