[PHP] 使用反射實現的控制反轉

搬家進程中反射實現控制反轉,樣作的好處是能夠經過配置項動態的控制下面那個類的屬性php


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);app

舉例:this

/*
這樣作的好處是能夠經過配置項動態的控制下面那個類的屬性
*/

//配置項
$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);

各個屬性正確賦值:3d

相關文章
相關標籤/搜索