<?php namespace app\models; use yii\base\Object; use yii\db\Connection; use yii\di\Container; // 定义接口 interface UserFinderInterface { function findUser(); } // 定义类,实现接口 class UserFinder extends Object implements UserFinderInterface { public $db; // 从构造函数看,这个类依赖于 Connection public function __construct(Connection $db, $config = []) { $this->db = $db; parent::__construct($config); } public function findUser() { } } class UserLister extends Object { public $finder; // 从构造函数看,这个类依赖于 UserFinderInterface接口 public function __construct(UserFinderInterface $finder, $config = []) { $this->finder = $finder; parent::__construct($config); } } //--------------------------下面是Di容器的使用方法----------------- /* 建立一个容器 */ $container = new Container; // 为Connection指定一个数组做为依赖,当须要Connection的实例时,使用这个数组进行建立 $container->set('yii\db\Connection', [ 'dsn' => '...',]); // 在须要使用接口 UserFinderInterface 时,采用UserFinder类实现 $container->set('app\models\UserFinderInterface', [ 'class' => 'app\models\UserFinder',]); // 为UserLister定义一个别名 $container->set('userLister', 'app\models\UserLister'); // 获取这个UserList的实例 $lister = $container->get('userLister');