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

2019-04-26 08:23:16来源:博客园 阅读 ()

新老客户大回馈,云服务器低至5折

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


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

举例:

/*
这样做的好处是可以通过配置项动态的控制下面那个类的属性
*/

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

各个属性正确赋值:

 

  

 


原文链接:https://www.cnblogs.com/taoshihan/p/10773463.html
如有疑问请与原作者联系

标签:

版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com
特别注意:本站所有转载文章言论不代表本站观点,本站所提供的摄影照片,插画,设计作品,如需使用,请与原作者联系,版权归原作者所有

上一篇:PostMan测试接口,绕过登录验证

下一篇:[PHP]日志处理error_log()函数和配置使用