通知通道扩展
2026/10/26大约 2 分钟
通知通道扩展(NotifyService)
基座通知中心内置 email、sms、inbox(站内信)三通道,push 通道由推送能力注册。插件可注册自定义通道(如钉钉、企业微信),注册后即可用同一套模板与 send/dispatch 发送,无需改动发送方代码。
注册通道
use app\basic\adapter\...; // 略
use app\service\NotifyService;
use app\model\system\Config;
// 写在 boot(),owner=插件名
NotifyService::register(
'webhook', // 通道类型标识
// 发送回调:fn(string $to, string $content, array $template, array $config): array
fn($to, $content, $template, $config) => [
'success' => MyWebhook::push($config, $to, $content, $template),
'message' => 'ok',
'data' => [],
],
// 配置解析:fn(NotifyTemplate $template): ?array,通常读该通道的配置组
fn($template) => Config::getConfig('webhook'),
skipPreference: false, // 内部通道(不受用户拒收偏好约束)设 true
owner: 'am_demo'
);- 发送回调必须返回
['success' => bool, 'message' => string, 'data' => mixed]。 $template已带渲染后的title、content、rendered_variables、log_id、extra。- 通道显示名与凭证表单同样走配置管理体系声明(
configSchema或install.sql),configResolver里用Config::getConfig('{通道}')读取,与基座邮件/短信配置同构。
发送(模板驱动)
注册后,发送方按通道类型调用基座统一入口即可:
// 同步单通道
NotifyService::send('order_paid', 'webhook', $receiver, ['order_no' => $no]);
// 同步多通道(一条日志记录各通道结果)
NotifyService::sendMulti('order_paid', [
'inbox' => $userId,
'webhook' => $hookUrl,
], $variables);
// 异步投递队列(事件驱动、无需即时结果时用)
NotifyService::dispatch('order_paid', ['webhook' => $hookUrl], $variables);异步走 send_notify
dispatch/dispatchOne 投递到 redis 队列 send_notify,由基座消费者执行;插件不需要写消费者。发送完成后基座 emit('notify.sent', ...),可被事件总线订阅。
判定与清理
| 方法 | 作用 |
|---|---|
getRegisteredTypes() | 内置 + 自定义的全部通道类型 |
hasRegisteredChannel($type) | 自定义通道是否已注册 |
forgetByOwner($owner) | 禁用/卸载时清理自定义通道(基座自动调用) |
进程级
register() 一律写在 boot(),传 owner。详见生命周期。
