PHP反射机制实现插件的可插拔设计

WBOY
Release: 2016-06-23 13:14:35
Original
981 people have browsed it

说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实现接口: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() . ” 载入中…
”;
}
}
?>Plugin2实现接口: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() . ” 载入中…
”;
}
}
?>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. 主页面输出菜单HTMLforeach ($menu as $m){
echo “{$m['text']} “;
}注意第6部就是PHP的反射操作,是不是很简单呢。分析下其中代码,一个完整的反射操作时机只有2行代码!$refClass = new ReflectionClass($class);
$menuItem = $refClass->getMethod(‘getMenu’)->invoke(null);好了,反射的基本功能就介绍到这了。当然了,PHP的反射功能不仅仅如此,有兴趣的自己发掘去吧。

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!