YII容器类依赖注入

程序 = 算法 + 数据结构

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

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

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

  use yii;
  use yii\web\Controller;
  use yii\di\Container;//容器类依赖注入

  class DependencyinjectController extends Controller{

      public function actionIndex()
      {
          $container = new Container();
          $container->set('frontend\controllers\Driver','frontend\controllers\ManDriver');
          //get方法首先实例化ManDriver,再以其返回值传递给Car
          $car = $container->get('frontend\controllers\Car');
          $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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值