灰太狼 2016-11-19 14:37:37 4672次浏览 4条评论 1 0 0

写了一个Yii2.0通用依赖注入接口实现类的结构。
还请大牛指点!

<?php
namespace backend\controllers;
/**
 * Description of Test
 *
 */
use yii\base\Controller;
class TestController extends Controller {
    //put your code here
    /**
     * 依赖注入   
     */
    public function actionDiclass(){
        $class = 'Marks';
//        $class = 'Marks1';    //切换实现类
        $quantity = new \common\DIClass($this->_class($class));
        $name = $quantity->getName('小小虾');
        $age = $quantity->getAge(25);
        echo $name."--".$age;die;
    }
    private function _class($class){
        switch ($class) {
            case 'Marks':
                return new \common\Marks(); 
                break;
            case 'Marks1':
                return new \common\Marks1(); 
                break;
            default:
                break;
        }
    }
}
namespace common;
/**
 * 定义类实现接口的方法
 *
 * @author 
 */
class Marks implements MarksInterface{
    //put your code here
    
    public function getName($name){
        return "Yii2.0开发者333:".$name;
    }
    
    public function getAge($age){
        return "今年已经222:".$age."岁了!";
    }
}

<?php
namespace common;
/**
 * Description of Mark1
 *
 */
class Marks1 implements MarksInterface{
    //put your code here
    
    public function getName($str){
        return "1111";
    }
    
    public function getAge($str){
        return "2222";
    }
}
<?php
/*
 * 接口
 */
namespace common;
/**
 *
 */
interface MarksInterface {
    //put your code here
    public function getName($data);
    
    public function getAge($data);
}

输出结果:Yii2.0开发者333:小小虾--今年已经222:25岁了!

您需要登录后才可以评论。登录 | 立即注册