主题
04 插件系统
支持的插件类型
定义于 PluginService::TYPES:
| type | 用途 | 基类 |
|---|---|---|
addon | 功能扩展(日志、通知等) | app\common\lib\Plugin |
gateway | 支付网关 | GatewayPlugin → GatewayInterface |
sms | 短信驱动 | SmsPlugin → SmsDriverInterface |
mail | 邮件驱动 | MailPlugin → MailDriverInterface |
certification | 实名认证 | CertificationPlugin → RealnameProviderInterface |
server / reserver / oauth | 魔方兼容目录 | Plugin |
生命周期
上传/市场安装 → 磁盘有文件 → 后台「安装」→ install() → kd_addons 登记 → enable
启用 → 加载 hooks.php
停用 → status=0,钩子不再加载
卸载 → uninstall() → 删除 kd_addons主类必须实现的方法(按需)
php
public function install() // 建表等,返回 true/false
public function uninstall() // 删表等
public function enable() // 启用时
public function disable() // 停用时配置读写继承自 Plugin::getConfig() / setConfig(),合并 config.php 与数据库。
最小 addon 示例
目录 public/plugins/addon/hello_world/
HelloWorld.php
php
<?php
namespace addon\hello_world;
use app\common\lib\Plugin;
class HelloWorld extends Plugin
{
public $info = [
'name' => 'HelloWorld',
'title' => 'Hello 示例',
'description' => '演示插件',
'author' => 'Your Name',
'version' => '1.0.0',
];
public function install() { return true; }
}hooks.php
php
<?php
add_hook('after_user_register', function ($param) {
// 用户注册后逻辑
});config.php
php
<?php
return ['enabled' => 1];钩子注册
全局函数(app/common.php):
php
add_hook('hook_name', callable $fn, int $priority = 50);
run_hook('hook_name', $params);触发时使用 CamelCase 或 snake_case 均可,例如:
HookService::trigger('UserLogin', ...)同时匹配user_login- 魔方别名:
AfterInvoicePaid→order_paid
常用钩子见 11-钩子系统。
后台 API
| 接口 | 说明 |
|---|---|
GET /admin/addon/index?type=addon | 扫描本地插件 |
POST /admin/addon/install | 安装 |
POST /admin/addon/uninstall | 卸载 |
POST /admin/addon/enable / disable | 启停 |
GET/POST /admin/addon/config | 读写配置 |
权限模块:plugin
与业务系统集成
| 能力 | 接入方式 |
|---|---|
| 支付 | 实现 GatewayInterface,driver 键 plugin:payjs |
| 短信/邮件 | 实现对应 Interface,安装后在系统设置选驱动名 |
| 实名 | 实现 RealnameProviderInterface,后台选 plugin:http_api |
详见 06–08 章。
从市场 / 压缩包安装
插件有两种安装方式,详见 05-插件市场:
| 方式 | 场景 |
|---|---|
| 压缩包安装 | 生产、内网:解压到 public/plugins/,在 本地插件 Tab 安装 |
| 开发环境安装 | 配置 MARKETPLACE_SERVER,在 插件市场 Tab 一键安装 |
不支持插件市场离线部署;生产环境请勿依赖
resources/marketplace/packages/。
下一章:05-插件市场