refactor: 修改Api返回封装

This commit is contained in:
2025-01-04 15:12:10 +08:00
parent 8ff1cbdac7
commit 8570b65a8c
3 changed files with 85 additions and 7 deletions

View File

@@ -3,26 +3,26 @@
// 接口错误返回
if (!function_exists('error')) {
function error($msg = '', $data = []): \think\response\Json
function error($msg = '', $data = [], $status_code = 200): \think\response\Json
{
return \apiret\Api::error($msg, $data);
return \apiret\Api::error($msg, $data, $status_code);
}
}
// 接口成功返回
if (!function_exists('success')) {
function success($msg = '', $data = []): \think\response\Json
function success($msg = '', $data = [], $status_code = 200): \think\response\Json
{
return \apiret\Api::success($msg, $data);
return \apiret\Api::success($msg, $data, $status_code);
}
}
// 接口调结果返回
if (!function_exists('result')) {
function result($errno, $msg = '', $data = []): \think\response\Json
function result($errno, $msg = '', $data = [], $status_code = 200): \think\response\Json
{
return \apiret\Api::result($errno)->message($msg)->response($data);
return \apiret\Api::result($errno)->message($msg)->response($data, $status_code);
}
}

1
extend/.gitignore vendored
View File

@@ -1,2 +1 @@
*
!.gitignore

79
extend/apiret/Api.php Normal file
View File

@@ -0,0 +1,79 @@
<?php
namespace apiret;
class Api
{
private static $response;
private $state = [];
private $config = [
'status_var' => 'status',
'message_var' => 'message',
'data_var' => 'data',
'states' => [
'success' => [
'status' => 200,
'message' => '操作成功!',
'data' => []
],
'error' => [
'status' => 2001,
'message' => '操作错误!',
'data' => []
],
]
];
private function __construct($errno)
{
isset($errno) || die('请确认返回类型!');
$this->config = config('apiret');
$this->state = $this->config['states'][$errno];
return $this;
}
// 单例
public static function result($errno): Api
{
if (!self::$response) {
self::$response = new self($errno);
}
return self::$response;
}
// 写入返回信息
public function message($message=''): Api
{
$message ? $this->state[$this->config['message_var']] = $message : '';
return $this;
}
// 返回错误
public static function error($msg='', $data=[], $status_code = 200): \think\response\Json
{
$ins = self::result('error');
if ($msg) {
$ins = $ins->message($msg);
}
return $ins->response($data, $status_code);
}
// 返回成功
public static function success($msg='', $data=[], $status_code = 200): \think\response\Json
{
$ins = self::result('success');
if ($msg) {
$ins = $ins->message($msg);
}
return $ins->response($data, $status_code);
}
// 返回结果
public function response($data=[], $status_code = 200): \think\response\Json
{
$this->state[$this->config['data_var']] = $data;
return \think\Response::create($this->state, 'json', $status_code);
}
}