Files
NewTicket/app/common/Trait/ApiResponse.php
2026-08-05 11:06:20 +08:00

48 lines
1.2 KiB
PHP

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