定义目录
├─plugin // 插件目录
│ ├─plugin1 // 插件1
│ │ ├─config.php // 插件1的配置项
│ │ ├─index.php // 插件1的程序处理内容
│ ├─plugin2
│ │ ├─config.php
│ │ ├─index.php
│ ├─plugin3
│ │ ├─config.php
│ │ ├─index.php
│ ├─...
├─index.php // 业务逻辑
业务逻辑
<?php
class Test{
public function index(){
// 用户注册成功
// 获取全部插件
$pluginList=scandir('./plugin/');
// 循环插件 // 排除. ..
foreach ($pluginList as $k => $v) {
if ($v=='.' || $v=='..') {
unset($pluginList[$k]);
}
}
echo "简易后台管理<hr>";
// 插件管理
foreach ($pluginList as $k => $v) {
// 获取配置项
$config=include './plugin/'.$v.'/config.php';
$word=$config['status']==1 ? '点击关闭' : '点击开启';
echo $config['title'].'<a href="./index.php?change='.$v.'">'.$word.'</a><br />';
}
echo '<hr>';
// 输出插件内容
foreach ($pluginList as $k => $v) {
// 获取配置项
$config=include './plugin/'.$v.'/config.php';
if ($config['status']==1) {
include './plugin/'.$v.'/index.php';
// 运行插件
Hook::run($v);
}
}
// 前往网站首页
}
}
// 插件类
class Hook{
// 注册添加插件
public static function add($name,$func){
$GLOBALS['hookList'][$name][]=$func;
}
// 执行插件
public static function run($name,$params=null){
foreach ($GLOBALS['hookList'][$name] as $k => $v) {
call_user_func($v,$params);
}
}
}
// 更改插件状态
if (isset($_GET['change'])) {
// 获取到配置项
$config=include './plugin/plugin'.substr($_GET['change'],-1).'/config.php';
// 如果是开启 那就关闭 如果是关闭 则开启
$config['status']=$config['status']==1 ? 0: 1;
// 将更改后的配置项写入到文件中
$str="<?php \r\n return ".var_export($config,true).';';
file_put_contents('./plugin/'.$_GET['change'].'/config.php', $str);
header('Location:./');
}
$test=new Test();
$test->index();
插件配置项
<?php
return array (
'status' => 1, // 定义状态 1表示开启 0表示关闭
'title' => '发送短信', // 插件的名称
);
插件内容
<?php
Hook::add('plugin1',function(){
echo '发送短信的内容<br />';
});
首先是插件经理类PluginManager,这个类要放在全局引用里面,在所有需要用到插件的地方,优先加载。
接下来是一个简单插件的实现DEMO_actions。这是一个简单的Hello World插件,用于输出一句话。在实际情况中,say_hello可能包括对数据库的操作,或者是其他一些特定的逻辑。
再接下来就是插件的调用触发的地方,比如我要将say_hello放到我博客首页Index.php, 那么你在index.php中的某个位置写下:
第一个参数表示钩子的名字,第二个参数是插件对应方法的入口参数,由于这个例子中没有输入参数,所以为空。