本文实例讲述了php基于反射机制实现插件的可插拔设计。分享给大家供大家参考,具体如下:
说php和asp等同的朋友们可以就此打住了,php支持反射,而且还是非常的强大。好了,我们开始今天的话题。
功能描述:
页面拥有一个主导航菜单,里头有默认连接若干。
插件统一存放在一个目录,插件载入后会自动在导航菜单中增加上自己所需的链接。
插件载入时可执行一定的操作。
动态增删插件无需改动代码。
最终效果:
首页,插件1,插件2
"首页"是系统自带的菜单项。"插件1"和"插件2"是由插件注册的菜单项。
实现过程:
1. 文件结构
learn
plugin
plugin1.php
plugin2.php
test.php
如此设计后,页面入口为test.php,插件都存放在plugin目录下,只要遍历plugin目录就可以找到所有的插件了。
2. 设计插件接口
interface iplugin{
static function getname();
static function init();
static function getmenu();
}
3. 插件内部实现接口
plugin1实现接口:
<?php
class welcome implements iplugin{
static function getname(){
return 'welcome (plugin)';
}
static function getmenu(){
return array(
'text'=>'插件1′,
'href'=>'http://www.google.com'
);
}
static function init(){
echo self::getname() . " 载入中…<br />";
}
}
?>
plugin2实现接口:
<?php
class showad implements iplugin{
static function getname(){
return 'show ad (plugin)';
}
static function getmenu(){
return array(
'text'=>'插件2′,
'href'=>'http://www.live.com'
);
}
static function init(){
echo self::getname() . " 载入中…<br />";
}
}
?>
4. 主页面初始化主导航菜单
$menu[] = array( 'text'=>'首页', 'href'=>'/test.php' );
5. 遍历插件目录,载入全部插件
$pluginpath = $_server['document_root'] . '/plugin';
$dirhd = opendir($pluginpath);
while ($file = readdir($dirhd)){
$pluginfilepath = $pluginpath . '/' . $file;
if($file!='.' && $file!='..' && is_file($pluginfilepath)){
include "$pluginfilepath";
}
}
6. 过滤出实现了iplugin接口的插件,并执行插件注入操作。
// 反射执行方法(注入菜单)
foreach (get_declared_classes() as $class){
$refclass = new reflectionclass($class);
if($refclass->implementsinterface('iplugin')){
//插件初始化
$refclass->getmethod('init')->invoke(null);
//获取注入菜单
$menuitem = $refclass->getmethod('getmenu')->invoke(null);
//合并菜单项
$menu = array_merge($menu, array($menuitem));
}
}
7. 主页面输出菜单html
foreach ($menu as $m){
echo "<a href='{$m['href']}'>{$m['text']}</a> ";
}
注意第6部就是php的反射操作,是不是很简单呢。分析下其中代码,一个完整的反射操作时机只有2行代码!
$refclass = new reflectionclass($class);
$menuitem = $refclass->getmethod('getmenu')->invoke(null);
好了,反射的基本功能就介绍到这了。当然了,php的反射功能不仅仅如此,有兴趣的自己发掘去吧。
更多关于php相关内容感兴趣的读者可查看本站专题:《php数组(array)操作技巧大全》、《php排序算法总结》、《php常用遍历算法与技巧总结》、《php数据结构与算法教程》、《php程序设计算法总结》、《php数学运算技巧总结》、《php正则表达式用法总结》、《php运算与运算符用法总结》、《php字符串(string)用法总结》及《php常见数据库操作技巧汇总》
希望本文所述对大家php程序设计有所帮助。
【说明】:本文章由站长整理发布,文章内容不代表本站观点,如文中有侵权行为,请与本站客服联系(QQ:)!