跳到主要内容
星衍社区
社区/插件开发文档,开发插件说明
程序中心开放讨论

插件开发文档,开发插件说明

admin830 条回复

LiteBBS 插件开发文档

插件开发文档


1. 目录结构

plugins/<plugin-id>/
├── plugin.json              # 必需,唯一清单文件
├── src/                     # 必需(PHP 只能放这里)
│   └── Plugin.php
├── migrations/              # 可选,结构迁移
│   └── 20261201_1200_create_tables.php
└── assets/                  # 可选,静态资源
    ├── style.css
    └── app.js

约束(运行时强制):

  • 目录名与 plugin.json.id 必须一致,格式 ^[a-z][a-z0-9_-]{1,31}$。

  • 文件总数 ≤ 300,单文件 ≤ 2 MiB,不允许符号链接、隐藏文件/目录。

  • 允许扩展名:json php css js png jpg jpeg gif webp svg txt md map。

  • PHP 文件只能位于 src/ 或 migrations/。

  • PHP 预检禁止:eval/include/require/exit/global,exec/shell_exec/system/passthru/proc_open/popen/pcntl_exec,curl_exec/curl_multi_exec/fsockopen/stream_socket_client,putenv/ini_set/set_error_handler/register_shutdown_function,get_defined_vars/ReflectionClass/ReflectionFunction/class_alias,以及直接读取 $GLOBALS/$_ENV/$_SERVER。


2. plugin.json 字段

{
  "schema": 1,
  "id": "friend-links",
  "title": "友情链接",
  "description": "在侧边栏展示友情链接",
  "version": "1.0.1",
  "requires": { "core": ">=1.0 <2.0" },
  "entry": "src/Plugin.php",
  "class": "FriendLinksPlugin",
  "permissions": ["database", "routes", "views", "assets"],
  "hooks": { "slots": ["sidebar.sections"] },
  "anonymous_cache_slots": ["sidebar.sections"],
  "public_route_prefix": "friend-links",
  "assets": ["assets/style.css"],
  "database_tables": ["plg_friend_links_links"],
  "admin_path": "links"
}
字段必填规则
schema是必须为整数 1
id是与目录名一致,^[a-z][a-z0-9_-]{1,31}$
version是严格 x.y.z,升级必须大于已安装版本,禁止降级
requires.core是形如 >=1.0 <2.0(>=下限 <上限),必须匹配当前 LITEBBS_VERSION
entry是src/**/*.php,不能越界
class是合法 FQCN,实现 LiteBBSPlugin
title / description否展示用元数据
permissions是最多 16 项,取值仅 database storage routes views assets security services,不可重复
dependencies否{ "其他插件": "版本约束" },安装/启用时校验
conflicts否同结构,启用冲突插件时拒绝
integrations否同结构,可选集成探测
capabilities否{ "核心能力": "版本约束" },如 admin.plugin-pages、forms、jobs、metrics、uploads、notifications、search、user.fields、theme.views
hooks视需要声明插件会使用的钩子;未声明的钩子不会加载该插件
anonymous_cache_slots否必须是 hooks.slots 的子集;声明后该槽位允许进入匿名页缓存
public_route_prefix注册前台路由时必填小写,保留前缀不可用:admin plugin plugin-assets assets uploads install login logout register me new search market robots sitemap t c u p avatar messages topic post report user
assets否字符串数组或 {path, pages, common};pages 见第 11 节
database_tables使用数据库时必填≤100 张,必须以 plg_<id下划线化>_ 开头,不可重复
admin_path否插件管理页短名,^[a-z][a-z0-9_-]{0,63}$
entries否{ "功能项": true/false } 默认开关
services否只能声明 topic-view-counter
signals使用信号时必填{"publishes":[],"subscribes":[]},发布名必须以 <id>. 开头
links否清单级导航链接,见第 10 节
autoload否{ "Vendor\\Pkg\\": "src/" },≤16 项,路径必须在 src/ 下

hooks 可声明的键与注册器一一对应:

"hooks": {
  "middleware": ["request.before"],
  "slots": ["sidebar.sections"],
  "preloads": ["topic.replies"],
  "events": ["topic.created.v2", "topic.deleted"],
  "renderers": ["post.markdown"],
  "filters": ["post.rendered"],
  "selections": ["home"],
  "read_transforms": ["category"],
  "views": ["home", "pagination"]
}

commands、policies、services、extensions 是顶层字段,不放在 hooks 内。

extensions 能力开关

以下功能必须先置为 true 才会加载:

"extensions": {
  "post_actions": true,
  "post_views": true,
  "topic_lists": true,
  "profile_tabs": true,
  "public_profile_tabs": true,
  "notification_tabs": true,
  "notification_presenters": true,
  "avatar_providers": true,
  "seo_providers": true,
  "authentication_providers": true,
  "navigation_links": true,
  "search": true,
  "tasks": true
}

3. 入口类与 PluginContext

<?php
declare(strict_types=1);

use LiteBBS\Framework\Request;
use LiteBBS\Framework\Response;

final class DemoPlugin implements LiteBBSPlugin
{
    public function boot(PluginContext $context): void
    {
        $context->slots()->add('sidebar.sections', static function (array $view): string {
            return ($view['path'] ?? '') === '/' ? '<aside>演示</aside>' : '';
        });

        $context->routes()->front('GET', '~^/demo/ping$~', static function (Request $request): Response {
            return (new Response())->json(['ok' => true]);
        });
    }
}

PluginContext 公开方法及所需权限:

方法返回所需 permission
id()插件 ID—
routes()PluginRouteRegistrarroutes
requests()PluginRequestRegistrarsecurity
lifecycle()PluginBootRegistrar—
slots()PluginSlotRegistrarviews
preloads()PluginPreloadRegistrarviews
events()PluginEventRegistrar—
signals()PluginSignalRegistrar—
assets()PluginAssetRegistrarassets
content()PluginContentRegistrarviews
filters()PluginFilterRegistrarviews
readSelections() / readTransforms() / views()PluginSurfaceRegistrarviews
database()PluginDatabasedatabase
settings()PluginSettingsdatabase
cache()PluginCache—
logger()PluginLogger—
admin()PluginAdminRegistrarviews
forms()PluginForms—
tasks()PluginTaskRegistrardatabase
metrics()PluginMetrics—
uploads()PluginUploadsstorage
notifications()PluginNotificationsdatabase
search()PluginSearchRegistrardatabase
userFields()PluginUserFieldsdatabase
commands() / policies()注册器views
postActions() / navigation() / postViews()注册器views
topicLists() / publicProfiles() / profiles()注册器views
notificationTabs() / notificationPresenters()注册器views
avatars() / seo()注册器views
authentication()注册器security
services()注册器services
read()CoreReadRepository—
urls()PluginUrlGenerator—
config()清单配置数组—

4. 生命周期与迁移

后台/市场统一走 extension_plugin_lifecycle($id, $action, $preserveData, $approvedByAdmin),动作仅:

动作规则
install校验清单与依赖,执行迁移,默认 enabled=0
upgrade新版本必须严格大于已安装版本,执行待应用迁移
enable磁盘版本必须等于登记版本;校验依赖后启用
disable检查是否有启用插件依赖它
uninstallpreserveData=true 时保留表与迁移账本;false 时校验表归属后删除

迁移文件:

  • 路径 migrations/YYYYmmdd_HHmmss_slug.php(示例 20261201_1200_create_tables.php)。

  • 文件只能返回字面量 SQL 字符串数组,不允许函数调用、变量、条件、循环等 PHP 逻辑。

  • SQL 中引用的 plg_ 表必须属于当前插件前缀。

  • 结构变更只能走迁移;运行时 database()->query() 只允许单条 SELECT/INSERT/UPDATE/DELETE,禁止 ALTER/CREATE/DROP/TRUNCATE/GRANT/...、分号和注释。

  • 已应用迁移的 SHA-256 会登记到 plugin_migrations。若插件包修改了已应用的迁移文件,升级会被拒绝(Applied migration checksum changed);管理员显式执行升级时框架会重登记校验和并继续,不会重跑该迁移,同时写日志 plugin migration checksum re-baselined。


5. 路由与中间件

$context->routes()->front('GET', '~^/demo/items$~', $handler);
$context->routes()->front(['GET','POST'], '~^/demo/items/(?P<id>[1-9][0-9]*)$~', $handler, [
    'auth' => 'user',   // public | user | moderator | admin
    'csrf' => true,     // 仅允许 POST 使用
]);
  • 必须声明 public_route_prefix,路由正则必须精确匹配 ^/<prefix> 且以 $ 结尾,不允许 | 分支。

  • 状态变更必须用 POST;csrf=true 只对 POST 生效。

  • 禁止重复注册同一 pattern + method。

  • 请求中间件:$context->requests()->before(fn(Request $r): ?Response => null, $priority),返回 Response 即中断请求。


6. 钩子总表

6.1 槽位(slot,返回 HTML 字符串)

head.assets, navigation.primary, page.content.before, page.content.after,
login.form.fields.after, login.form.after, register.form.fields.after, register.form.after,
member.profile.form.after, page.main.before, page.main.after, page.header.after,
page.footer.before, sidebar.sections, footer.before, body.end,
home.feed.before, home.feed.after, category.header.after, category.feed.before, category.feed.after,
topic.create.fields, topic.create.sidebar, topic.edit.fields, topic.edit.sidebar,
topic.header.after, topic.actions.after, topic.thread.before, topic.thread.after,
post.before, reply.create.fields, reply.create.sidebar, reply.edit.fields, reply.edit.sidebar,
reply.form.after, post.edit.fields, post.edit.form.after, profile.header.after,
profile.content.after, post.after-body, post.after, admin.head, admin.navigation,
admin.content.before, admin.content.after

6.2 预加载(preload,返回 void)

home.feed.items, category.feed.items, topic.replies,
notification.list, post.after-body, post.after

用于在列表渲染前批量取数据,配合 PluginPreloadContext::put()/get() 做到逐条渲染零查询。

6.3 过滤器(filter)

名称输入 → 输出说明
post.markdown.sourcemarkdown → markdown严格模式,禁止 SQL
post.renderedhtml → html渲染后 HTML
post.rowhtml → html/null帖子行
view.documenthtml → html/null整页文档

严格过滤器输出必须是字符串或 null,执行预算 0.1s;失败会记录日志并把插件标记为 degraded。

6.4 视图覆盖(view)

可覆盖:layout、home、category、topic、pagination、account.login、account.register、profile、search、member、messages。

$context->views()->provide('pagination', static fn(array $data): string => '...', 0);

优先级:插件 view > 主题包视图 > 核心回退。返回 null 表示交给下一层。

6.5 事件

推荐使用 v2(严格校验 payload):

事件模式字段
topic.create.preflight.v2syncactor_id, title, body, category_id, uploads
topic.deleting.v2synctopic_id, category_id, actor_id, post_ids
topic.created.v2synctopic_id, post_id, actor_id, title, body, category_id, uploads
post.created.v2synctopic_id, post_id, actor_id, body, uploads
post.updated.v2synctopic_id, post_id, actor_id, body, previous_body_markdown
post.deleting.v2syncpost_id, topic_id, category_id, actor_id, reason
topic.updated.asyncasynctopic_id, actor_id, title, category_id, previous_title, previous_category_id
topic.created.asyncasynctopic_id, post_id, actor_id
post.created.asyncasynctopic_id, post_id, actor_id
notification.createdasyncnotification_id, recipient_id, actor_id, kind, topic_id, post_id
topic.deletedasynctopic_id, category_id, post_ids, actor_id, reason
post.deletedasyncpost_id, topic_id, actor_id, reason
topic.moderatedasynctopic_id, category_id, action, value, actor_id
category.created / category.updatedasynccategory_id, actor_id
category.visibility.updatedasynccategory_id, visible, actor_id
reaction.created / reaction.deletedasyncpost_id, topic_id, actor_id, reaction
bookmark.created / bookmark.deletedasynctopic_id, actor_id
subscription.created / subscription.deletedasynctopic_id, actor_id
report.created / report.reviewedasyncreport_id, target_type, target_id, actor_id (+status)
user.registered / user.profile.updated / user.avatar.updatedasyncuser_id
user.updatedasyncuser_id, actor_id, role, status, is_developer
user.blocked / user.unblockedasyncactor_id, user_id

同步事件在写请求内执行,单监听器预算 10ms;超时或抛异常会把插件标记为 degraded 并中断请求。耗时工作请用异步事件或任务。

旧版 v1 事件(topic.create.preflight、topic.created、post.created、post.updated、topic.deleting)自 1.1 起弃用,仅在有监听器时记录弃用日志。

$context->events()->listen('topic.created.v2', static function (array $p): void {
    // $p['topic_id'], $p['post_id'], ...
});

异步事件写入 outbox,由后台任务消费;extension_enqueue_async_event() 在事务内调用可随写入一起回滚。

6.6 信号(插件间)

"signals": { "publishes": ["demo.item.created"], "subscribes": ["other.item.updated"] }
$context->signals()->emit('demo.item.created', ['id' => 1]);
$context->signals()->listen('other.item.updated', static function (array $p): void {});

未在清单声明会抛异常;发布名必须以插件 ID 为前缀。


7. 权限与政策

$context->policies()->allow('topic.create', static function (PolicyContext $ctx): string {
    return ($ctx->actor()['role'] ?? '') === 'admin' ? PolicyDecision::Allow : PolicyDecision::Abstain;
});
  • extension_permits($ability, $context):任一插件返回 deny/false 即拒绝;插件异常时失败关闭;无启用插件时直接放行。

  • extension_authorize():拒绝时返回 403。

  • extension_authorize_speaking($actor, $action, $subject):固定走 user.can_speak,$action 仅 topic.create topic.reply topic.edit post.edit。

可用能力:

category.view, topic.view, attachment.download,
topic.create, topic.reply, topic.edit, post.edit, topic.delete, post.delete,
profile.view, user.username_reserved, user.can_speak

政策上下文只读,通过 actor()、subject('topic')、all() 或数组方式访问。


8. 数据、缓存与设置

$db = $context->database();
$table = $db->table('items');            // plg_demo_items
$rows = $db->query('SELECT id,title FROM '.$table.' WHERE status=? ORDER BY id DESC LIMIT 20', ['active'])->fetchAll();
  • 运行时只允许单条 DML,且只能引用本插件前缀的表。

  • 建表/改表必须写迁移。

$context->cache()->remember('sidebar', 60, static fn(): array => [...]);
$context->cache()->forget('sidebar');
  • key 格式 ^[a-z][a-z0-9._:-]{0,95}$,值必须可 JSON 编码。

  • 缓存自动带版本号,settings()->save() 或插件失效会推进版本。

$config = $context->settings()->get();
$values = $context->settings()->values($schema);
$context->settings()->save(['api_key' => '...']); // ≤64 KiB

9. 常用注册器速查

注册器方法
routes()front($methods, $pattern, $handler, $options = [])、add() 同义
requests()before($handler, $priority = 0)
lifecycle()onRequest($handler, $priority = 0)
slots()add($slot, $renderer, $priority = 0)
preloads()add($slot, $loader)
events()listen($event, $listener)
signals()emit($signal, $payload = [])、listen($signal, $listener)
assets()css($path, $pages = ['all'])、js($path, $pages = ['all'])、require($path)、json($data)
content()markdown($renderer, $priority = 0)(只取最高优先级一个)
filters()add($filter, $handler, $priority = 0)
views()provide($surface, $handler, $priority = 0)
readSelections()provide($surface, $handler, $priority = 0),surface 仅 home/category/topic
readTransforms()同上,只能重排当前页已有 ID
admin()page($path, $title, $handler, $options = [])
forms()create()->field()->validate()->values()->errors()->render()
tasks()register($name, $handler, $options = [])、enqueue($name, $payload = [], $idempotencyKey = '', $delaySeconds = 0)
metrics()observe($op, $ms, $sqlCount = 0, $error = false)、status($status)、snapshot()
uploads()store($file, $allowedMime, $maxBytes = 5242880)
notifications()send($userId, $actorId, $kind, $topicId = null, $postId = null)
search()provider($name, $search)、index($documentId, $title, $body, $url)、remove($id)、invalidate()
userFields()register($name, $label, $rules = [])、get($userId, $name)、set($userId, $name, $value)
commands()filter($command, $handler, $priority = 0)
policies()allow($ability, $handler, $priority = 0)
postActions()add(PostAction)、provide(PostActionProvider)
navigation()add(NavigationLink)
postViews()decorate($handler, $priority = 0)
topicLists()titleSuffix($renderer, $priority = 0)、column(TopicListColumn)
publicProfiles()tab(PublicProfileTab)
profiles()tab(ProfileTab)
notificationTabs()tab(NotificationTab)
notificationPresenters()add(NotificationPresenter)
avatars()provide(AvatarProvider)
seo()contribute($provider, $priority = 0)
authentication()afterPassword($provider, $priority = 0)
services()replace($service, $factory, $priority = 0)、decorate(...),目前仅 topic-view-counter

命令白名单:topic.create reply.create topic.update post.update post.delete user.profile.update。

任务选项:retries(1–25,默认 10)、lease(30–3600 秒,默认 300)、every(60–2592000 秒,0 表示仅手动)、payload(JSON 兼容)。


10. 导航链接(无需主题配合)

清单级:

"links": [
  {
    "surface": "navigation.primary",
    "id": "demo-docs",
    "label": "文档",
    "href": "/demo/docs",
    "when": "all",
    "priority": 0,
    "parameters": {}
  }
]

可用 surface:navigation.primary、admin.navigation、sidebar.sections、page.header.after、page.footer.before、profile.header.after、home.feed.before、category.header.after、topic.actions.after。

when 取值 all/guest/member/admin;parameters 只能从 viewer_id/topic_id/category_id/profile_username 取值拼查询串。

运行时注册需开启 extensions.navigation_links:

$context->navigation()->add(new NavigationLink('demo-docs', '文档', '/demo/docs'));

ID 必须以 <plugin-id>- 开头。


11. 静态资源与匿名页缓存

"assets": [
  { "path": "assets/style.css", "pages": ["all"] },
  { "path": "assets/topic.js", "pages": ["topic.view"], "common": false }
]
  • pages 允许:all manual home category topic.view topic.create post.edit account.login account.register profile member search messages plugin admin,最多 16 个。

  • common: true 时 pages 必须为 ["all"]。

  • URL 形如 /plugin-assets/<id>/<path>?v=<hash>,带强缓存与 ETag。

  • 运行时 assets()->css()/js() 会按当前页面自动输出;assets()->require($path) 用于“实际渲染后才加载”的场景。

匿名页缓存:

  • 任何未声明为 anonymous_cache_slots 的槽位输出,都会让对应页面绕过公共页缓存。

  • 只有确定与访客无关的槽位才可声明;含用户态数据的槽位不要声明。


12. 性能与可靠性规范

  1. 同步事件单监听器预算 10ms;禁止在同步事件里做 HTTP、批量写库、复杂渲染。

  2. 严格过滤器禁止 SQL;列表逐条渲染逻辑用 preloads 预取。

  3. 分页只用 keyset(before/after),禁止 OFFSET、LIMIT n,m。

  4. 热点查询用 cache()->remember(),key 带业务维度;写后 forget()。

  5. 不要在 boot() 里做查询;boot() 只做注册。

  6. 大表索引要写进迁移;升级前在测试库验证。

  7. 外部请求只能通过框架允许的方式(插件运行时不提供网络 API),避免在请求内同步调用第三方。

  8. 输出必须转义;槽位/视图返回的 HTML 由插件自行负责安全。


13. 故障排查

日志/现象含义处理
Deployed plugin manifest must match the installed ID and version.磁盘清单与数据库登记版本/ID 不一致,运行时跳过插件后台升级到磁盘版本,或恢复匹配的安装包
Applied migration checksum changed: ...已应用迁移文件被改写管理员执行升级触发受控重登记,或恢复原迁移文件
plugin migration checksum re-baselined: ...升级时已重登记校验和,未重跑该迁移确认插件功能正常;后续改动请新增迁移
plugin sync event ... exceeded 10ms budget同步监听器超预算,插件被降级改为异步事件/任务
plugin ... failed / degraded回调抛异常查看插件日志;修复后重新启用
插件完全不生效plugin.json 未在 hooks 中声明对应钩子补声明后重载插件
Plugin must declare the xxx permission.PluginContext 方法所需权限缺失在 permissions 中补充

插件日志:$context->logger()->error('...') 输出 plugin[<id>] ...。