Files
orico-official-website/extend/apiret/Api.php
2025-01-04 15:12:10 +08:00

80 lines
1.9 KiB
PHP

<?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);
}
}