YII服务定位器依赖注入
2016-05-26 09:40
435 查看
<?php /** * Created by PhpStorm. * Date: 2016/5/25 * Time: 18:33 * 服务定位器依赖注入 */ namespace frontend\controllers; use yii; use yii\web\Controller; use yii\di\Container; use yii\di\ServiceLocator; class DependencyinjectserviceController extends Controller{ public function actionIndex() { Yii::$container->set('frontend\controllers\Driver','frontend\controllers\ManDriver'); $sl = new ServiceLocator(); $sl->set('Car',[ 'class'=>'frontend\controllers\Car', ]); $car = $sl->get('Car'); $car->run(); /* 'car' =>['frontend\controllers\Driver','frontend\controllers\ManDriver'];可以配置在config components中 这时 Yii::$app->car->run();*/ /*板块2 * Yii::$container->set('frontend\controllers\Driver','frontend\controllers\ManDriver'); Yii::$app->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(Driver $driver)//第20行实现接口传递 ,消除强依赖 { $this->driver = $driver; } public function run() { $this->driver->drive(); } }
config.php
<?php $config = [ 'components' => [//应用组件 'request' => [ // !!! insert a secret key in the following (if it is empty) - this is required by cookie validation 'cookieValidationKey' => 'fvfpjzSKyDScNsrOXvd8f8atT6CY0rVj', ], 'car' =>[ 'class'=>'frontend\controllers\Car' ], ], ]; if (!YII_ENV_TEST) { // configuration adjustments for 'dev' environment $config['bootstrap'][] = 'debug'; $config['modules']['debug'] = [ 'class' => 'yii\debug\Module', ]; $config['bootstrap'][] = 'gii'; $config['modules']['gii'] = [ 'class' => 'yii\gii\Module', ]; } return $config;
相关文章推荐
- YII容器类依赖注入
- YII类的映射表机制
- YII页面缓存
- php 数组 常用函数
- 如何修改php内存限制
- 每天laravel-20160815| Container -18
- 每天laravel-20160815| Container -18
- PHP新的垃圾回收机制:Zend GC详解
- 基于PHP实现数据分页显示功能
- PHP高手干货分享:不能不看的50个细节!
- Windows下搭建PHP开发环境
- PHP使用curl替代file_get_contents
- PHP语言的RSA算法加解密程序
- php array_filter过滤数组为空值
- php preg_match_all函数笔记
- php urlencode()与urldecode()函数字符编码原理-笔记
- PHP实现数据分页显示
- php的异常和处理
- weiphp机制浅析
- 基于PHP实现数据分页显示功能