<?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');
Yii2中DI(依賴注入)的使用方法案例
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.