initearth / think-response
为 ThinkPHP 8 API 项目提供规范统一的响应数据结构
Requires
- php: ^8.4
- ext-json: *
- initearth/think-enum: ^4.0
- topthink/framework: ^8.1
Requires (Dev)
- friendsofphp/php-cs-fixer: ^3.95
- pestphp/pest: ^5.0
- phpstan/phpstan: ^2.3
- phpstan/phpstan-strict-rules: ^2.1
- phpunit/phpunit: ^13.4
Suggests
None
Provides
None
Conflicts
None
Replaces
None
README
为 ThinkPHP 8.1 API 提供统一响应结构、业务码语义与异常响应。遵循 ThinkPHP 8 开发规范(PSR-2 / PSR-4、目录小写下划线、类文件与类名一致、方法小驼峰、配置小写下划线)。
特性
- 四个意图入口:
success()、redirect()、error()、fail(),参数顺序统一 html()模板入口:使用think-view渲染模板,留空使用内置默认模板,不套用 JSON 响应结构- 固定五字段响应:
status、code、message、data、error - 3 位 HTTP 状态码与 6 位业务码,业务码前三位决定 HTTP 状态
- 业务码解析只有一条路径,默认
strict,非法码与意图不匹配直接抛异常 - 枚举消息、语言包与
BackedEnum业务码 - 统一格式化
Arrayable、JsonSerializable、toArray()对象与分页数据 - 构造函数注入与 IDE 友好 Facade 双入口
- 异常解析独立为
ExceptionMapper,处理器只做协商与委托 - 服务无状态,适用于 Think-Swoole 常驻内存场景
环境
| 依赖 | 版本 |
|---|---|
| PHP | ^8.4 |
| ThinkPHP | ^8.1 |
ext-json |
必需 |
topthink/think-view |
^2.0 |
initearth/think-enums |
GitHub main 固定提交(VCS 仓库 + composer.json 指定 #d0b5a00) |
上游 initearth/think-enums 未发布 tag/Packagist 版本,本项目通过 VCS 仓库依赖,并在 composer.json 中固定提交;不提交 composer.lock,CI 使用 composer install 解析该提交。
html() 使用 topthink/think-view 的 think 模板驱动;未配置 template_path 时,相对模板与内置默认模板都从本包的 src/template 目录解析。
安装
composer require initearth/think-response php think service:discover php think vendor:publish
检查解析结果:
php think response:config
快速开始
构造函数注入
use Initearth\ThinkResponse\Response; final class UserController { public function __construct(private readonly Response $response) { } public function index() { return $this->response->success(User::select(), '获取成功', 200000); } }
Facade
use Initearth\ThinkResponse\facade\Response; return Response::success(['id' => 1], '获取成功', 200000);
Facade 只委托容器中的 Response,@method static 文档块由测试保证与真实签名一致。
响应结构
{
"status": "success",
"code": 200000,
"message": "操作成功",
"data": {"id": 1},
"error": {}
}
| 字段 | 说明 |
|---|---|
status |
success、error、fail |
code |
业务码 |
message |
对外提示信息 |
data |
业务数据;空数据输出 {} |
error |
错误详情;空错误输出 {} |
status 由业务码推导:1xx/2xx/3xx 为 success,4xx 为 error,5xx 为 fail。HTTP 状态为 204/205 时响应体为空。
API
四个意图方法参数顺序一致:(mixed $payload, string $message, BackedEnum|int $code, array $headers, array $options)。html() 为模板入口:(string $template, array $vars, BackedEnum|int $code, array $headers, array $options),通过 think-view 渲染 text/html 响应,不套用五字段结构;$template 留空时渲染内置默认模板。
public function success(mixed $data = null, string $message = '', BackedEnum|int $code = 200, array $headers = [], array $options = []): JsonResponse; public function redirect(mixed $data = null, string $message = '', BackedEnum|int $code = 302, array $headers = [], array $options = []): JsonResponse; public function error(mixed $errors = null, string $message = '', BackedEnum|int $code = 400, array $headers = [], array $options = []): JsonResponse; public function fail(mixed $errors = null, string $message = '', BackedEnum|int $code = 500, array $headers = [], array $options = []): JsonResponse; public function html(string $template = '', array<string, mixed> $vars = [], BackedEnum|int $code = 200, array<string, mixed> $headers = [], array<string, mixed> $options = []): ViewResponse;
$this->response->success(User::select(), '获取成功', 200000); $this->response->redirect(['url' => '/users/1'], '已迁移', 302, ['Location' => '/users/1']); $this->response->error(['email' => ['邮箱格式不正确']], '验证失败', 422001); $this->response->fail(null, '删除失败', 500001); $this->response->html('maintenance', ['message' => '维护中'], 503, ['Retry-After' => '3600']); $this->response->html('', ['title' => '通知', 'message' => '升级中']);
$template 为相对模板名(可省略 .html 后缀)时从 template_path 解析,为绝对路径时直接使用。html() 的 code 同样支持 BackedEnum 与业务码(取 HTTP 状态部分),默认 strict 策略下非法码会抛出 InvalidArgumentException;需要旧的归一化行为时显式配置 'code_policy' => 'coerce'。
业务码
- 3 位码:直接使用 HTTP 状态码,如
200、422 - 6 位码:
HTTP 状态码前三位 + 三位业务编号,如401005、200101
think-enums 内置业务码
think-enums 内置 Initearth\ThinkEnums\enums\HttpStatusCode,覆盖 Symfony HttpFoundation 定义的常用 HTTP 状态码(100–511)。它可直接作为 code 传入各响应入口,无需自定义,也无需注册到 enum:
use Initearth\ThinkEnums\enums\HttpStatusCode; $this->response->success(null, '', HttpStatusCode::OK); $this->response->error(null, '', HttpStatusCode::NOT_FOUND); $this->response->fail(null, '', HttpStatusCode::SERVICE_UNAVAILABLE); $this->response->html('', [], HttpStatusCode::SERVICE_UNAVAILABLE);
HttpStatusCode 是 int backed enum,枚举值就是 3 位 HTTP 状态码;它不是 6 位业务码,6 位业务码仍需按下一节自定义。通过 EnumEnhance 它提供 values()、hasValue()、tryFromValue()、fromValue() 等解析能力,并自带 statusClass()、isSuccess()、isRedirect()、isClientError()、isServerError() 分类方法:
HttpStatusCode::NOT_FOUND->isClientError(); // true HttpStatusCode::fromValue(503); // HttpStatusCode::SERVICE_UNAVAILABLE
内置枚举本身不内置文案;message 留空时,think-response 会先查语言包中的 HttpStatusCode 覆盖,再使用内置 HTTP 描述,最后回退到 default_message,详见「本地化业务码描述」。
自定义业务码
自定义业务码用 int 型 backed enum 表示。推荐实现 EnhancedEnum 并使用 EnumEnhance,以获得按值查 case、内置文案和本地化标签能力:
namespace App\Enums; use Initearth\ThinkEnums\contract\EnhancedEnum; use Initearth\ThinkEnums\support\EnumEnhance; enum ResponseCode: int implements EnhancedEnum { use EnumEnhance; case LOGIN_SUCCESS = 200101; case INVALID_TOKEN = 401005; case ORDER_MISSING = 404002; case SERVER_BUSY = 503001; public static function defaultMessages(string $group = EnhancedEnum::DEFAULT_GROUP): array { return $group === EnhancedEnum::DEFAULT_GROUP ? [ 'LOGIN_SUCCESS' => '登录成功', 'INVALID_TOKEN' => '登录已过期', 'ORDER_MISSING' => '订单不存在', 'SERVER_BUSY' => '服务繁忙', ] : []; } }
约束:
- 枚举必须是
intbacked enum;字符串 backed enum 与普通 enum 会被配置校验拒绝。 - 码值只能是
100–599的 HTTP 状态码,或100000–599999的 6 位业务码;6 位码前三位必须是受支持的 HTTP 状态码。 - 码值前三位决定 HTTP 状态:1xx/2xx 用于
success(),3xx 用于redirect(),4xx 用于error(),5xx 用于fail()。默认strict策略下意图不匹配会抛InvalidArgumentException。 EnhancedEnum/EnumEnhance不是强制要求;普通intbacked enum 也能按值匹配,但内置文案与标签能力需要自行实现。需要自定义描述逻辑时可实现Initearth\ThinkResponse\contract\DescribedEnum。
注册到 config/think_response.php:
'enum' => [ \App\Enums\ResponseCode::class, // 多个枚举按顺序查找 \App\Enums\JwtErrorCode::class, ],
调用时直接传枚举:
use App\Enums\ResponseCode; $this->response->success(null, '', ResponseCode::LOGIN_SUCCESS); $this->response->error(null, '', ResponseCode::INVALID_TOKEN);
显式传入的 message 优先级最高;留空时按「本地化业务码描述」小节的顺序回退。
注意上游 think-enums 新版的 FQCN:contract\EnhancedEnum、support\EnumEnhance、enums\HttpStatusCode、i18n\EnumI18n。
本地化业务码描述
业务码枚举注册到 enum 后,调用时把 message 留空即可按业务码查找对应枚举 case,并从当前语言集读取本地化描述。
语言包文件位于项目根目录 lang/<语言集>/<locale>.php。locale 默认为 enums,语言集跟随 ThinkPHP 的 Lang(如 zh-cn),所以默认文件是 lang/zh-cn/enums.php:
<?php return [ 'App\Enums\ResponseCode' => [ 'LOGIN_SUCCESS' => '登录成功', 'LOGIN_ERROR' => '登录失败', ], // 短类名可作为兜底,完整类名优先 'ResponseCode' => [ 'LOGIN_SUCCESS' => '登录成功', ], ];
键名为枚举类名(完整类名或短类名)到 case name => 文案 的映射;类名与 case 名均大小写不敏感。枚举也可以通过 EnhancedEnum::defaultMessages() 内置默认文案,语言包命中时优先使用语言包。若只剩 case 名格式化结果(如 Login Success),视为未配置描述,不参与消息回退。
修改为其他分组时,把配置 locale 设为对应文件名即可,例如 'locale' => 'api_messages' 会读取 lang/zh-cn/api_messages.php。
消息优先级为:显式传入的 message → 业务码枚举标签(语言包 / 枚举自带文案)→ messages 配置 → 枚举描述 → HTTP 状态标签 / 内置 HTTP 描述 → default_message。该机制只决定 message 字段;data、error 中枚举实例的输出方式由 enum_output 控制。
数据格式化
Formatter 递归处理 Arrayable、JsonSerializable、带 toArray() 的对象及嵌套数组,最大深度 64。空数据输出 {}。分页数据固定输出为 data.data 与 data.meta.pagination。
顶层结构始终只有 status、code、message、data、error 五个字段。
异常处理
启用内置处理器时,服务始终接管 think\exception\Handle。通过 json_mode 决定哪些请求返回 JSON:
negotiate(默认):Accept含 JSON 媒体类型、AJAX 或 JSON 请求体always:所有请求never:交还框架默认处理器
异常映射按继承距离匹配,距离按异常类缓存:
'exception' => [ 'enable' => true, 'json_mode' => 'negotiate', 'debug' => null, 'map' => [ \think\exception\ValidateException::class => [ 'code' => 422, 'message' => '验证失败', 'expose' => false, ], ], ],
expose = true 时用异常自身消息覆盖配置消息;未匹配异常只有在 debug 生效时才暴露原始消息。响应中不再附带调用栈或文件行号,详细异常信息交给框架日志。
实现 ResponsiveException 的异常优先提供业务码与消息:
use Initearth\ThinkResponse\contract\ResponsiveException; final class BusinessException extends \RuntimeException implements ResponsiveException { public function __construct(private readonly int $businessCode, ?string $message = null) { parent::__construct($message ?? '业务处理失败'); } public function responseCode(): int { return $this->businessCode; } public function responseMessage(): ?string { return $this->getMessage(); } }
配置参考
| 配置 | 默认值 | 说明 |
|---|---|---|
enum |
null |
业务码枚举类名或类名数组 |
locale |
enums |
语言包分组名 |
code_policy |
strict |
strict / coerce |
enum_output |
value |
value / description / label_value |
template_path |
'' |
html() 模板根目录,留空使用包内置 src/template |
messages |
200 / 500 中文消息 |
完整业务码对应消息 |
default_message |
成功/错误/失败中文 | 兜底消息 |
exception.enable |
true |
是否接管默认异常处理器 |
exception.json_mode |
negotiate |
negotiate / always / never |
exception.debug |
null |
是否暴露异常原始消息,null 跟随 app.debug |
exception.map |
见配置文件 | 异常类到响应规则的映射,完整替换默认规则 |
完整默认值见 src/config/think_response.php。
自定义格式化
容器绑定 Formatter 契约即可替换默认实现:
use Initearth\ThinkResponse\contract\Formatter; $this->app->bind(Formatter::class, \App\Support\ApiFormatter::class);
契约只有两个方法:format(Code $code, string $message, mixed $data = null, mixed $errors = null): array 与 paginate(Paginator $paginator): array。ArrayFormatter 继承该契约,便于其他包复用。
开发
composer test
composer analyse
composer cs-check
CI 在 PHP 8.4 下执行 composer validate、PHP-CS-Fixer(PSR-12)、PHPStan Level 9 + strict-rules 与 PHPUnit。
许可
Apache-2.0