您的位置:首页 > 运维架构 > 网站架构

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

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

整体思路是: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');
}
}

?>


结果

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: