php之反射调用类中方法 插件架构
2013-07-06 17:20
330 查看
今天在公司加班,项目里要用到其他的插件,为了减少代码侵入,就想用php 的反射机制应该是不错的,开始上网查资料(lz是android开发,在小公司你懂得),花了大概两个多小时完成了下面的代码。
整体思路是:pluginM通过读取配置文件demo.ini加载插件文件,而后通过反射的方式调用指定的方法。
pluginM文件
配置文件 demo.ini
插件测试代码 test1.php
test2.php
反射调用
结果
整体思路是:pluginM通过读取配置文件demo.ini加载插件文件,而后通过反射的方式调用指定的方法。
pluginM文件
<?php class 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,test2 classpath=application/plugin/test1.php;application/plugin/test2.php
插件测试代码 test1.php
<?php class test1 { function __construct() { } function init(){ echo "test1 init"; } function run(){ echo "test1 run"; } function sayHello($name){ echo "test1 say hello ".$name; } } ?>
test2.php
<?php class test2 { function __construct() { } function init(){ echo "test2 init"; } function run(){ echo "test2 run"; } function sayHello($name){ echo "test2 say hello ".$name; } } ?>
反射调用
<?php class plugin extends CI_Controller { function __construct(){ parent::__construct(); $this->load->model('pluginM'); } function index(){ $this->pluginM->run('test2',"sayHello",' Tom'); } } ?>
结果
相关文章推荐
- PHP 反射机制详解 以及插件架构实现
- 用php反射实现插件的自动调用
- PHP 反射机制详解 以及插件架构实现
- PHP通过反射方法调用执行类中的私有方法
- php反射机制以及利用php反射机制实现可插拔可扩展的插件架构
- PHP 反射机制详解 以及插件架构实现
- php调用第三方插件ffmpeg获取上传视频信息方法
- 反射调用private方法实践(php、java)
- php利用反射实现插件机制的方法
- php利用反射实现插件机制的方法
- 反射调用private方法实践(php、java)
- PHPdragon framework(3.1) 用php反射实现插件的自动调用
- PHP通过反射机制调用可变参数方法
- PHP通过反射实现对象的成员方法调用
- 在PHP中使用反射技术的架构插件使用说明
- Eclipse RCP 插件开发中经常调用的几个方法(转载)
- PHP使用PDO调用mssql存储过程的方法示例
- Java反射 根据不同方法名动态调用不同的方法
- 跟着辛星用PHP的反射机制来实现插件