init: 项目初始代码
This commit is contained in:
101
extend/apiRes/Api.php
Normal file
101
extend/apiRes/Api.php
Normal file
@@ -0,0 +1,101 @@
|
||||
<?php
|
||||
namespace apiRes;
|
||||
|
||||
class Api
|
||||
{
|
||||
private static $response;
|
||||
private $state = [];
|
||||
|
||||
private $default_states = [
|
||||
'success' => [
|
||||
'errno' => 0,
|
||||
'errmsg' => '操作成功!',
|
||||
'data' => []
|
||||
],
|
||||
'error' => [
|
||||
'errno' => 2001,
|
||||
'errmsg' => '操作错误!',
|
||||
'data' => []
|
||||
],
|
||||
'NoData' => [
|
||||
'errno' => 2002,
|
||||
'errmsg' => '没有数据!',
|
||||
'data' => []
|
||||
],
|
||||
'NotLoggedIn' => [
|
||||
'errno' => 2003,
|
||||
'errmsg' => '未登录',
|
||||
'data' => []
|
||||
]
|
||||
];
|
||||
|
||||
private function __construct($erro)
|
||||
{
|
||||
isset($erro) || die('请确认返回类型!');
|
||||
$this->state = $this->default_states[$erro];
|
||||
return $this;
|
||||
}
|
||||
|
||||
// 单例
|
||||
public static function result($erro)
|
||||
{
|
||||
if (!self::$response) {
|
||||
self::$response = new self($erro);
|
||||
}
|
||||
return self::$response;
|
||||
}
|
||||
|
||||
// 返回错误
|
||||
public static function error($msg='', $data=[], $to_array=false)
|
||||
{
|
||||
$ins = self::result('error');
|
||||
if ($msg) {
|
||||
$ins = $ins->message($msg);
|
||||
}
|
||||
|
||||
return $ins->response($data, $to_array);
|
||||
}
|
||||
|
||||
// 返回成功
|
||||
public static function success($msg='', $data=[], $to_array=false)
|
||||
{
|
||||
$ins = self::result('success');
|
||||
if ($msg) {
|
||||
$ins = $ins->message($msg);
|
||||
}
|
||||
|
||||
return $ins->response($data, $to_array);
|
||||
}
|
||||
|
||||
// 写入返回信息
|
||||
public function message($message='')
|
||||
{
|
||||
$message ? $this->state['errmsg'] = $message : '';
|
||||
return $this;
|
||||
}
|
||||
|
||||
// 返回结果
|
||||
public function response($data=[], $to_array=false)
|
||||
{
|
||||
if (!empty($data)) {
|
||||
$this->state['data'] = $data;
|
||||
}
|
||||
if (request()->isJson() || $to_array) {
|
||||
$output = $this->state;
|
||||
} else {
|
||||
$output = json_encode($this->state, JSON_UNESCAPED_UNICODE);
|
||||
}
|
||||
return $output;
|
||||
}
|
||||
|
||||
/**
|
||||
* 转成数组
|
||||
*/
|
||||
public function toArray()
|
||||
{
|
||||
if (is_array($this->state)) {
|
||||
return $this->state;
|
||||
}
|
||||
return json_decode($this->state, true);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user