• PHP 反射API


    在框架中,反射用的比较多,是一种比较灵活的统一实例化类,规范化接口,用起来很方便,废话不多说,直接上代码,例子看懂基本就会用php的反射了,主要部分已添加注释;不明白的可以留言给我。

    interface module{
        function execute();
    }
    class ftpModule implements module{
        function setHost($host){
            print "ftpModule::setHost():$host
    ";
        }
        function setUser($user){
            print "ftpModule::setUser():$user
    ";
        }
        function execute()
        {
            
        }
    }
    
    class moduleRun{
        private $configData=array(
            'ftpModule'=>array('host'=>'www.ceshi.com','user'=>'bob'),
        );
        private $modules = array();//缓存对象
    
        function init(){
            $interface = new ReflectionClass('Module');
            foreach($this->configData as $modulename=>$params){
                $module_class = new ReflectionClass($modulename);
                if( ! $module_class->isSubclassOf($interface)){
                    throw new Exception("unknow module type");
                }
                $module = $module_class->newInstance();//创建module示例
                foreach ($module_class->getMethods() as $method){
                    $this->handleMethod($module,$method,$params);
                }
                array_push($this->modules,$module);//缓存对象
            }
            return $this->modules;
        }
    
        function handleMethod(Module $module,ReflectionMethod $method,$params){
            $name =$method->getName();
            $args = $method->getParameters();
            if(count($args) != 1 || substr($name,0,3) != 'set'){
                return false;
            }
            $property = strtolower(substr($name,3));
    
            if(! isset($params[$property])){
                return false;
            }
            $arg_class =$args[0]->getClass();
            if(empty($arg_class)){
                $method->invoke($module,$params[$property]);//调用set方法
            }else{
                $method->invoke($module,$arg_class->newInstance($params[$property]));
            }
    
        }
    
    
    }
    
    $moduleRun = new moduleRun();
    $moduleRun->init();
  • 相关阅读:
    Rotate Always Encrypted keys using SQL Server Management Studio
    ABP Web Application Development Tutorial Part 1: Creating the Server Side
    Fiddler 2 Wipes My Internet Explorer Proxy Settings
    API设计浅析
    泛型的实现浅谈
    搜狗workflow异步调度框架
    MQTT 和 CoAP
    深入理解左值、右值
    C++ 头文件接口设计浅谈
    Windows无Internet但能正常上网的问题
  • 原文地址:https://www.cnblogs.com/happy-dream/p/6610145.html
Copyright © 2020-2023  润新知