读完这篇你会知道:两种都叫 Service 的东西分别是什么、
register()与boot()的边界在哪、耗时任务为什么要投队列、以及事件监听器为什么不该抛异常。
先分清两种 Service
代码里到处都是 "Service",但它们是两件完全不同的东西:
| 类型 | 长什么样 | 干嘛的 |
|---|---|---|
| 框架 Service | extends think\Service,在 app/service.php 注册 | 启动期装配:容器绑定、命令、扩展点、事件监听 |
| 业务 Service | app/common/service/ 下的普通 PHP 类 | 具体业务,如 QueueService、ExportService、CacheService |
关键差异:业务 Service 是普通 PHP 类,不走 DI 容器。use 进来直接 new,或者用静态入口,不需要门面、也不需要容器绑定。把它当"放业务逻辑的文件夹"来用就够了。
register() 与 boot() 的分工
app/service.php 注册的框架服务包含 AppService、LangPackService、ExtendLoaderService,以及 admin\Service、install\Service 这类应用级服务。它们的加载发生在 App::load() 阶段,早于 HTTP 管线:
loadEnv → App::load()
→ app/common.php
→ runtime/config.php(存在则用,否则 loadConfig())
→ app/event.php → app/service.php
→ HttpRun 触发,MultiApp 切换应用后再加载 app/{name}/ 下的配置/事件/中间件分工判断标准很简单:
register():只做"不需要框架完全就绪"的事——绑定容器、注册命令、登记扩展点;boot():做"需要基础设施就绪"的事——挂路由、监听事件、加载额外配置。
ExtendLoaderService 是这份分工的样板:register() 里只遍历 $ext['services'] 逐个 $this->app->register(),boot() 里才挂事件监听。
有一个必须放 register() 的特例:语言包。 App::loadLangPack() 早于服务 boot(),错过 register() 这个时机,该语言范围就再也不会被重载——表现是"语言文件写了但页面没变"。
业务 Service 的写法
约定是可选的 $config 数组,合并优先级:类默认值 < 配置文件 < 数据库配置 < 调用方覆盖。
class SomeService
{
protected array $config = ['timeout' => 30, 'retries' => 3];
public function __construct(array $config = [])
{
$this->config = array_merge($this->config, config('some_service', []), $config);
}
}必需键缺失时回退 env() 或抛出明确异常,并提供 getConfig() / setConfig() 便于测试覆盖。
四种使用模式:
| 模式 | 范例 | 什么时候用 |
|---|---|---|
直接 new | new UploadService() | 无状态业务,最常见 |
| 单例 | QueueService::instance() | 初始化昂贵(如 RSA 密钥)或需共享状态 |
| 静态方法 | CacheService::getCategories() | 纯缓存 / 工具封装 |
| 工厂 | AttachmentStore::driver() | 多态驱动选择 |
队列:HTTP 路径只投递,不执行
导出、通知、AI 生成、Webhook 回调这类耗时动作,一律投递队列,由常驻 worker 消费。请求里 sleep、exec、同步发邮件,在 FPM 下拖慢一个用户,在 Swoole 下拖死整个协程池。
Queue::push(SendNotificationJob::class, $data, 'notification');
Queue::later(1800, SendNotificationJob::class, $data, 'notification'); // 30 分钟后常用队列名:
| 队列 | 用途 |
|---|---|
default | 通用任务 |
notification | 多通道通知发送 |
webhooks | Webhook 发送与接收处理 |
export | 异步列表导出 |
worker 要按队列分别起:
php think queue:work --queue=notification --daemon
php think queue:work --queue=webhooks --daemon
php think queue:work --queue=export --daemon失败任务管理:
php think queue:failed # 列出
php think queue:retry <job_id> # 重试单个
php think queue:retry all # 全部重试
php think queue:forget <job_id> # 忘掉
php think queue:flush # 清空config/queue.php 里配置 default 驱动、stores 与失败表。生产必须配失败表,否则失败任务直接消失。
worker 没跑起来的典型症状:任务停在"等待中"、导出下载中心永远没有文件、投稿永远停在待审核。
事件:三种注册方式
Event::listen('event.name', Listener::class); // 监听
Event::bind('event.name', fn (...) => ...); // 绑定可调用响应
Event::subscribe(EventSubscriber::class); // 订阅者,批量注册配置文件加载时机不同,这点常被忽略:
config/event.php:应用初始化期加载,全局生效;app/{app}/event.php:应用切换后才加载,只在该应用的路由命中时生效。
插件里注册的事件在 PluginLoader 阶段完成,全局生效,与当前进入哪个应用无关。
内置事件大致分四类,出问题时按类去查:
| 分组 | 事件 |
|---|---|
| 请求 | HttpRun / HttpEnd(RequestContext 的清理就在这) |
| 插件生命周期 | plugin.installed / uninstalling / uninstalled / enabled / disabled |
| 能力与任务 | CapabilityToggled、TaskExecuteFailed、CrontabAlertEvent、WebhookFailed |
| 会员领域 | MemberCheckedIn 等 14 个,接到奖励链 |
自定义事件的最小闭环:
// 事件
final class OrderShipped
{
public function __construct(public readonly int $orderId) {}
}
// 监听器
final class NotifyBuyer
{
public function handle(OrderShipped $event): void
{
Notification::channel(['email', 'database'])->send(/* ... */);
}
}
Event::listen(OrderShipped::class, NotifyBuyer::class);
Event::trigger(new OrderShipped($order->id));监听器只做通知,不要抛异常阻断主流程。 生命周期事件的监听器抛异常只记 warning,不影响安装结果;业务事件里抛异常则可能让已经落库的操作看起来"失败了",重试一次就是重复数据。
事件与扩展点怎么接起来
AppService 把框架事件系统桥接成扩展点的事件派发器:
ExtPoint::bindEventDispatcher(static function (object $event): void {
\think\facade\Event::trigger($event);
});于是各包可以直接 Event::listen(CapabilityToggled::class, ...) 订阅能力启停,而 ExtPoint 自身保持零依赖——未绑定派发器时静默不派发。扩展点本身的用法见扩展点 ExtPoints 与槽位。
四个容易搞错的认知
一、"Service 要注册到容器里才能用"。 业务 Service 不需要;只有 think\Service 那类启动装配服务才进 app/service.php。
二、"队列投递成功就等于任务成功"。 投递只进队列,消费失败进失败表。看状态要看 queue:failed,不是看接口返回。
三、"事件监听写在控制器里也一样"。 控制器里 Event::listen 只在该请求内有效,下一请求就没了。
四、"语言包放 boot() 里注册也行"。 不行,boot() 时 loadLangPack() 已经跑完,语言不会生效。