[PHP] 使用反射实现的控制反转

2019-09-10 10:57:49 浏览数 (3)

搬家进程中反射实现控制反转,样做的好处是可以通过配置项动态的控制下面那个类的属性

1.$this->getObject($class, $config->getConfig('param'), array($this), $interfaces); 2.$reflection=new ReflectionClass($class); 3.$reflection->implementsInterface($interface)//检测是否实现接口 4.$obj=$reflection->newInstanceArgs() 5.$reflection->hasMethod($method)//检测是否有这个方法 6.$obj->$method($v);

举例:

代码语言:javascript复制
/*
这样做的好处是可以通过配置项动态的控制下面那个类的属性
*/

//配置项
$conf=array(
        'class'=>'User',
        'newParams'=>array('name'=>'taoshihan'),
        'setParams'=>array(
                'score'=>'100fen',
                'age'=>'100'
        )   
);
//业务类
class User {
    private $name;
    private $age;
    private $score;
    public function __construct($name){
        $this->name=$name;
    }   
    public function setAge($age){
        $this->age=$age;
    }   
    public function setScore($score){
        $this->score=$score;
    }   
}
//生成对象
class Application{
        private $conf;
        public function __construct($conf){
                $this->conf=$conf;
        }   
        public function getAction(){
                $obj=$this->getObject($this->conf['class'],$this->conf['setParams'],$this->conf['newParams']);
                return $obj;
        }   
        public function getObject($class, $setParams = null, $newParams = array()){
                if (!$class) {
                        return null;
                }            
                $reflection = new ReflectionClass($class);
                $obj = $reflection->newInstanceArgs($newParams);    
                if (!empty($setParams)) {
                        foreach ($setParams as $k => $v) {    
                        $method = 'set' . ucfirst($k);
                        if ($reflection->hasMethod($method)) {    
                                $obj->$method($v);    
                        }}  
                }   
                return $obj;
        }
}

$app=new Application($conf);
$obj=$app->getAction();
var_dump($obj);

各个属性正确赋值:

0 人点赞