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');}}?>
结果
- php之反射调用类中方法 插件架构
- php调用类中方法
- JAVA 反射之方法调用
- JAVA反射之调用方法
- javaSE之方法反射调用
- 反射基础之方法调用
- 反射调用类方法
- php 类方法反射
- invoke方法反射调用类指定中方法
- php反射方式调用方法执行
- PHP 反射机制详解 以及插件架构实现
- php反射机制以及利用php反射机制实现可插拔可扩展的插件架构
- 反射之读取类信息、调用类属性和方法
- 用php反射实现插件的自动调用
- java中利用反射调用另一类的private方法
- java反射机制动态调用类中方法
- php中调用java类的方法
- 调用反射类的方法
- LINUX 虚拟网卡tun例子
- Android学习之3:文件的保存与读取
- Eclipse背景颜色修改+方案
- Friday解题报告
- POJ2449 第k最短路径
- php之反射调用类中方法 插件架构
- 一些设计图--关于代码生成
- java中的Math类
- 算法随想
- 支持向量机SVM分析
- poj 3159 Candies------spfa算法
- Bitmap和Drawable之间的转换
- Linux下安装启动多个Tomcat
- 介绍几本专业的书籍,一起学习