zoukankan      html  css  js  c++  java
  • YII服务定位器依赖注入

    <?php
    /**
     * Created by PhpStorm.
     * Date: 2016/5/25
     * Time: 18:33
     * 服务定位器依赖注入
     */
    namespace frontendcontrollers;
    
    use yii;
    use yiiwebController;
    use yiidiContainer;
    use yiidiServiceLocator;
    
    class DependencyinjectserviceController extends Controller{
        public function actionIndex()
        {
    
            Yii::$container->set('frontendcontrollersDriver','frontendcontrollersManDriver');
            $sl = new ServiceLocator();
            $sl->set('Car',[
                'class'=>'frontendcontrollersCar',
            ]);
            $car = $sl->get('Car');
            $car->run();
    
    
    
            /* 'car' =>['frontendcontrollersDriver','frontendcontrollersManDriver'];可以配置在config components中
             这时
             Yii::$app->car->run();*/
            /*板块2
             * Yii::$container->set('frontendcontrollersDriver','frontendcontrollersManDriver');
                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'=>'frontendcontrollersCar'
            ],
        ],   
    
    ];
    
    if (!YII_ENV_TEST) {
        // configuration adjustments for 'dev' environment
        $config['bootstrap'][] = 'debug';
        $config['modules']['debug'] = [
            'class' => 'yiidebugModule',
        ];
        $config['bootstrap'][] = 'gii';
        $config['modules']['gii'] = [
            'class' => 'yiigiiModule',
        ];
    }
    
    return $config;
  • 相关阅读:
    Wannafly挑战赛21A
    luoguP4000 斐波那契数列
    关于斐波那契数模意义下的循环节问题
    Codeforces Round #501 (Div. 3) F. Bracket Substring
    1257: [CQOI2007]余数之和
    51nod1380 夹克老爷的逢三抽一
    51nod1423 最大二"货" 单调栈
    51nod1624 取余最长路 前缀和 + set
    51nod1437 迈克步 单调栈
    51nod1515 明辨是非 并查集 + set
  • 原文地址:https://www.cnblogs.com/isuben/p/5529878.html
Copyright © 2011-2022 走看看