47 lines
1.2 KiB
PHP
47 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(int $code = 200, string $message = '操作成功', mixed $data = []): Json
|
|
{
|
|
return $this->jsonResponse($code, $message, $data);
|
|
}
|
|
|
|
/**
|
|
* 失败响应
|
|
* @param string $message 错误提示信息
|
|
* @param int $code 自定义业务状态码
|
|
* @param mixed $data 额外的错误数据(如验证未通过的具体字段)
|
|
* @return Json
|
|
*/
|
|
protected function error(int $code = 400, string $message = '操作失败', mixed $data = []): Json
|
|
{
|
|
return $this->jsonResponse($code, $message, $data);
|
|
}
|
|
|
|
/**
|
|
* 统一 JSON 返回格式
|
|
*/
|
|
private function jsonResponse(int $code, string $message, mixed $data): Json
|
|
{
|
|
$result = [
|
|
'code' => $code,
|
|
'msg' => $message,
|
|
'data' => $data,
|
|
];
|
|
|
|
return json($result);
|
|
}
|
|
}
|