YII容器类依赖注入

程序 = 算法 + 数据结构

数据结构 制约了 算法的===>>>>依赖注入

依赖注入也就是解数据结构和算法耦合的思想

<?php
/**
 * Created by PhpStorm.
 * Date: 2016/5/25
 * Time: 18:09
 * 容器类依赖注入
 */
  namespace frontendcontrollers;

  use yii;
  use yiiwebController;
  use yiidiContainer;//容器类依赖注入

  class DependencyinjectController extends Controller{

      public function actionIndex()
      {
          $container = new Container();
          $container->set('frontendcontrollersDriver','frontendcontrollersManDriver');
          //get方法首先实例化ManDriver,再以其返回值传递给Car
          $car = $container->get('frontendcontrollersCar');
          $car->run();
      }
  }
interface Driver{
    public function drive();
}
  class ManDriver implements  Driver{
      public function drive(){
          echo "I am an old man!";
      }
  }
  class Car{
      private $driver = null;
      //public function __construct(ManDriver $driver)//ManDriver 强关联,耦合太高,故使用接口
      public function __construct(Driver $driver)//第20行实现接口传递 ,消除强依赖
      {
        $this->driver = $driver;
      }
      public function run()
      {
          $this->driver->drive();
      }
  }
原文地址:https://www.cnblogs.com/isuben/p/5529863.html