This commit is contained in:
2026-07-20 14:59:16 +08:00
parent cd1175b304
commit 77930b3232
9 changed files with 94 additions and 78 deletions

View File

@@ -1,66 +1,46 @@
<?php
namespace app\common\Trait;
use think\Response;
use think\response\Json;
/**
* API 响应 Trait
* 提供统一的 JSON 响应格式
*/
trait ApiResponse
{
/**
* 成功响应
*
* @param mixed $data 响应数据
* @param string $msg 响应消息
* @param int $code 响应码
* @param int $httpCode HTTP状态码
* @return Response
* @param string $message 提示信息
* @param mixed $data 返回数据
* @param int $code 自定义业务状态码
* @return Json
*/
protected function successResponse($data = [], $msg = '成功', $code = 200, $httpCode = 200)
protected function success(int $code = 200, string $message = '操作成功', mixed $data = []): Json
{
return json([
'code' => $code,
'msg' => $msg,
'data' => $data
], $httpCode);
return $this->jsonResponse($code, $message, $data);
}
/**
* 错误响应
*
* @param string $msg 错误消息
* @param mixed $data 错误数据
* @param int $code 错误码
* @param int $httpCode HTTP状态码
* @return Response
* 失败响应
* @param string $message 错误提示信息
* @param int $code 自定义业务状态码
* @param mixed $data 额外的错误数据(如验证未通过的具体字段)
* @return Json
*/
protected function errorResponse($msg = '失败', $data = null, $code = 400, $httpCode = 400)
protected function error(int $code = 400, string $message = '操作失败', mixed $data = []): Json
{
return json([
'code' => $code,
'msg' => $msg,
'data' => $data
], $httpCode);
return $this->jsonResponse($code, $message, $data);
}
/**
* 自定义响应
*
* @param int $code 响应码
* @param string $msg 响应消息
* @param mixed $data 响应数据
* @param int $httpCode HTTP状态码
* @return Response
* 统一 JSON 返回格式
*/
protected function customResponse($code, $msg, $data = [], $httpCode = 200)
private function jsonResponse(int $code, string $message, mixed $data): Json
{
return json([
$result = [
'code' => $code,
'msg' => $msg,
'data' => $data
], $httpCode);
'msg' => $message,
'data' => $data,
];
return json($result);
}
}