码迷,mamicode.com
首页 > 其他好文 > 详细

理解依赖注入(Dependency Injection)

时间:2015-10-08 23:02:56      阅读:235      评论:0      收藏:0      [点我收藏+]

标签:

理解依赖注入

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

class SessionStorage
{
  function __construct($cookieName = ‘PHP_SESS_ID‘)
  {
    session_name($cookieName);
    session_start();
  }

  function set($key, $value)
  {
    $_SESSION[$key] = $value;
  }

  function get($key)
  {
    return $_SESSION[$key];
  }

  // ...
}

这是一个操作session的类 , 下面的user类要使用session中的功能

class User
{
  protected $storage;

  function __construct()
  {
    $this->storage = new SessionStorage();
  }

  function setLanguage($language)
  {
    $this->storage->set(‘language‘, $language);
  }

  function getLanguage()
  {
    return $this->storage->get(‘language‘);
  }

  // ...
}

// 我们可以这么调用

$user = new User();
$user->setLanguage(‘zh‘);

这样看起来没什么问题,但是user里写死了SessionStorage类,耦合性太强,不够灵活,需解耦。

优化后的user类代码

class User
{
  protected $storage;

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

  function setLanguage($language)
  {
    $this->storage->set(‘language‘, $language);
  }

  function getLanguage()
  {
    return $this->storage->get(‘language‘);
  }

  // ...
}

调用方法:

$storage = new SessionStorage(‘SESSION_ID‘);
$user = new User($storage);

不在User类中创建SessionStorage对象,而是将storage对象作为参数传递给User的构造函数,这就是依赖注入

依赖注入的方式

依赖注入可以通过三种方式进行:

构造器注入 Constructor Injection

刚才使用的这也是最常见的:

class User
{
  function __construct($storage)
  {
    $this->storage = $storage;
  }

  // ...
}

设值注入 Setter Injection

class User
{
  function setSessionStorage($storage)
  {
    $this->storage = $storage;
  }

  // ...
}

属性注入 Property Injection

class User
{
  public $sessionStorage;
}

$user->sessionStorage = $storage;

下面是Yii2的例子

// create a pagination object with the total count
$pagination = 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

理解依赖注入(Dependency Injection)

标签:

原文地址:http://www.cnblogs.com/mafeifan/p/4862403.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!