依赖注入
引子
<?php class MovieLister { public function moviewsDirectedBy($directorName){ $finder = new MovieFinder(); //两个类有了强耦合关系 $allMovies = $finder->findAll(); $resultMovies = []; foreach ($allMovies as $movie){ if($movie->getDirector() == $directorName){ $resultMoviews[] = $movie; } } } } //程序=算法+数据结构 数据结构跟算法要剥离 优化: public function moviewsDirectedBy($directorName,$finder){ $finder = $finder->findAll(); .... .... }
Yii框架使用 - 容器(定义+解决依赖关系)
use yii\di\container Class ManDriver implements Driver{ public function drive(){ echo 'i am a driver'; } } interface Driver{ //用接口去除强关联 public function driver(); } class Car { private $driver = null; public function _construst(Driver $driver){ $this->driver = $driver; } public function run(){ $this->driver->drive(); } } //配置文件事先配置好,统一处理依赖关系 $container = new Container; $car = $container->set('app\models\Driver',"app\models\ManDriver"); //$driver = new ManDriver; //$car = Car($driver); $car = $container->get('app\models\Car'); $car->run();
Yii框架使用 - 服务定位器(配置服务参数)
use yii\di\ServiceLocation \Yii::$container->set('app\models\Driver',"app\models\ManDriver"); $s1 = new ServiceLocator; $s1->set('car'[ 'class' => 'app\models\Car', ]); $car = $s1->get('car') //可放在配置文件里统一配置,应用主体实际上就是一个服务定位器 compents => [ 'car' => [ 'class' => '\app\models\Car' ] ] \Yii::$container->set('app\models\Driver',"app\models\ManDriver"); \Yii::$app->car-run(); //加载时会在动解决依赖关系