• 理解依赖注入(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

  • 相关阅读:
    django系列5.4--ORM中执行原生SQL语句, Python脚本中调用django环境
    Cookie背景了解
    [leetcode] 832. Flipping an Image
    [leetcode] 888. Fair Candy Swap
    [leetcode] 66. Plus One
    0000:Deep Learning Papers Reading Roadmap
    [算法]时间复杂度
    [leetcode] 771. Jewels and Stones
    [cs231n] Convolutional Neural Networks for Visual Recognition
    推翻自己,从头来过
  • 原文地址:https://www.cnblogs.com/mafeifan/p/4862403.html
Copyright © 2020-2023  润新知