php之反射调用类中方法 插件架构

来源:互联网 发布:社会学stata数据库 编辑:程序博客网 时间:2024/05/22 01:50

        今天在公司加班,项目里要用到其他的插件,为了减少代码侵入,就想用php 的反射机制应该是不错的,开始上网查资料(lz是android开发,在小公司你懂得),花了大概两个多小时完成了下面的代码。

       整体思路是:pluginM通过读取配置文件demo.ini加载插件文件,而后通过反射的方式调用指定的方法。

      pluginM文件

<?phpclass pluginM extends CI_Model {function __construct(){parent::__construct();}function run($classname,$functionname,$par){$pluginarray =$this->get_ini_file("demo.ini");$classpathStr = $this->get_ini_item($pluginarray,'classpath');$classpatharr = explode(";",$classpathStr);for($i=0;$i<count($classpatharr);$i++){$classpath = $classpatharr[$i];require_once ($classpath);}$classnameStr=$this->get_ini_item($pluginarray,'classname');if(strpos($classnameStr,$classname)<0){echo "class  no find ";break;}$reflectionClass = new ReflectionClass($classname);$cla= $reflectionClass->newInstance();if(method_exists($cla, $functionname)){$function=$reflectionClass->getmethod($functionname);$function->invoke($cla,$par);}}function get_ini_file($file_name = "demo.ini"){$str=file_get_contents($file_name);$ini_list = explode("\r\n",$str);$ini_items = array();foreach($ini_list as $item){$one_item = explode("=",$item);if(isset($one_item[0])&&isset($one_item[1]))                             $ini_items[trim($one_item[0])] = trim($one_item[1]);}return $ini_items;}function get_ini_item($ini_items = null,$item_name = ''){if(empty($ini_items)) return "";else return $ini_items[$item_name];}}?>

配置文件 demo.ini

classname=test1,test2classpath=application/plugin/test1.php;application/plugin/test2.php

插件测试代码 test1.php 

<?phpclass test1  {function __construct(){} function init(){echo "test1  init";} function run(){echo "test1 run";}function sayHello($name){echo "test1 say hello ".$name;}}?>

 test2.php

<?phpclass test2  {function __construct(){} function init(){echo "test2  init";} function run(){echo "test2 run";}function sayHello($name){echo "test2 say  hello ".$name;}}?>

反射调用

<?phpclass plugin extends CI_Controller {function __construct(){parent::__construct();$this->load->model('pluginM');}function  index(){$this->pluginM->run('test2',"sayHello",' Tom');}}?>

结果 


原创粉丝点击