码迷,mamicode.com
首页 > 其他好文 > 详细

YII服务定位器依赖注入

时间:2016-05-26 10:07:34      阅读:150      评论:0      收藏:0      [点我收藏+]

标签:

<?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服务定位器依赖注入

标签:

原文地址:http://www.cnblogs.com/isuben/p/5529878.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!