理解依赖注入
Yii2.0 使用了依赖注入的思想。正是使用这种模式,使得Yii2异常灵活和强大。千万不要以为这是很玄乎的东西,看完下面的两个例子就懂了。
@H_502_6@class SessionStorage { @H_502_6@function __construct($cookieName = 'PHP_SESS_ID') { session_name($cookieName); session_start(); } @H_502_6@function set($key,$value) { $_SESSION[$key] = $value; } @H_502_6@function get($key) { @H_502_6@return $_SESSION[$key]; } // ... }
这是一个操作session的类 , 下面的user类要使用session中的功能
@H_502_6@class User { @H_502_6@protected $storage; @H_502_6@function __construct() { $this->storage = @H_502_6@new SessionStorage(); } @H_502_6@function setLanguage($language) { $this->storage->set('language',$language); } @H_502_6@function getLanguage() { @H_502_6@return $this->storage->get('language'); } // ... }
//我们可以这么调用
$user = @H_502_6@new User(); $user->setLanguage('zh');
这样看起来没什么问题,但是user里写死了SessionStorage类,耦合性太强,不够灵活,需解耦。
优化后的user类代码
@H_502_6@class User { @H_502_6@protected $storage; @H_502_6@function __construct($storage) { $this->storage = $storage; } @H_502_6@function setLanguage($language) { $this->storage->set('language',$language); } @H_502_6@function getLanguage() { @H_502_6@return $this->storage->get('language'); } // ... }
不在User类中创建SessionStorage对象,而是将storage对象作为参数传递给User的构造函数,这就是依赖注入。
依赖注入的方式
依赖注入可以通过三种方式进行:
构造器注入Constructor Injection
刚才使用的这也是最常见的:
@H_502_6@class User { @H_502_6@function __construct($storage) { $this->storage = $storage; } // ... }
设值注入Setter Injection
@H_502_6@class User { @H_502_6@function setSessionStorage($storage) { $this->storage = $storage; } // ... }
属性注入Property Injection
下面是Yii2的例子
// create a pagination object with the total count $pagination = @H_502_6@new Pagination(['totalCount' => $count]); // limit the query using the pagination and retrieve the articles $articles = $query->offset($pagination->offset) ->limit($pagination->limit) ->all();
参考:http://fabien.potencier.org/what-is-dependency-injection.html