zoukankan      html  css  js  c++  java
  • 理解依赖注入(Dependency Injection)

    理解依赖注入

    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

  • 相关阅读:
    Word 2007 测试
    全硬盘安装Win Vista 6000 RTM方法(转)
    Javascript 解析,格式化日期 (转)
    转:使用hgfs实现vmare文件传输一法,无需任何网络相关设置
    配置和运行版本验证测试(转自msdn)
    TFS错误一则(資料集 'IterationParam' 的查詢執行失敗)
    ghostdoc 1.9.5 for vista install
    January 2007 Community Technology Preview 1 安装
    Changing to a friendly Team Foundation Server Name (舶来品)
    命令行使用小结
  • 原文地址:https://www.cnblogs.com/mafeifan/p/4862403.html
Copyright © 2011-2022 走看看