<?PHP/** * Created by Phpstorm. * DATE:2016/5/25 * time:18:33 * Service locator Dependency Injection*/namespace Frontend\controllers; UseYii; UseYii\web\controller; UseYii\di\container; UseYii\di\servicelocator;classDependencyinjectservicecontrollerextendscontroller{ Public functionActionindex () {Yii::$container->set (' Frontend\controllers\driver ', ' frontend\controllers\mandriver '); $SL=NewServicelocator (); $SL->set (' Car ',[ ' Class ' = ' Frontend\controllers\car ', ]); $car=$SL->get (' Car '); $car-run (); /*' car ' =>[' frontend\controllers\driver ', ' frontend\controllers\mandriver '; can be configured in config components at this time Yii:: $app->car->run ();*/ /*Plate 2 * Yii:: $container->set (' frontend\controllers\driver ', ' frontend\controllers\mandriver '); Yii:: $app->car->run (); */ }}Interfacedriver{ Public functionDrive ();}classMandriverImplementsdriver{ Public functionDrive () {Echo"I am an old man! "; }}classcar{Private $driver=NULL; Public function__construct (Driver$driver)//Line 20th implements interface delivery, eliminating strong dependencies { $this->driver =$driver; } Public functionrun () {$this->driver->Drive (); }}
config.php
<?PHP$config= [ ' Components ' = [//Application Components' Request ' = [ //!!! Insert a secret key in the following (if it was 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 Service Locator Dependency Injection