82 行
2.1 KiB
PHP
82 行
2.1 KiB
PHP
<?php
|
|
namespace Api\Controller;
|
|
use Think\Controller;
|
|
|
|
/**
|
|
* API基础控制器
|
|
* 提供通用的API功能和验证
|
|
*/
|
|
class BaseController extends Controller {
|
|
|
|
/**
|
|
* 初始化方法
|
|
*/
|
|
public function _initialize() {
|
|
// 设置返回格式为JSON
|
|
header('Content-Type: application/json; charset=utf-8');
|
|
// 允许跨域
|
|
header('Access-Control-Allow-Origin: *');
|
|
header('Access-Control-Allow-Methods: GET, POST, OPTIONS');
|
|
header('Access-Control-Allow-Headers: Content-Type, Authorization, Token');
|
|
|
|
// 处理OPTIONS请求
|
|
if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
|
|
exit();
|
|
}
|
|
}
|
|
|
|
/**
|
|
* 返回成功响应
|
|
* @param mixed $data 数据
|
|
* @param string $message 消息
|
|
* @param int $code 状态码
|
|
*/
|
|
protected function success($data = null, $message = 'success', $code = 200) {
|
|
$this->ajaxReturn([
|
|
'status' => 1,
|
|
'code' => $code,
|
|
'message' => $message,
|
|
'data' => $data
|
|
]);
|
|
}
|
|
|
|
/**
|
|
* 返回错误响应
|
|
* @param string $message 错误消息
|
|
* @param int $code 错误码
|
|
* @param mixed $data 数据
|
|
*/
|
|
protected function error($message = 'error', $code = 400, $data = null) {
|
|
$this->ajaxReturn([
|
|
'status' => 0,
|
|
'code' => $code,
|
|
'message' => $message,
|
|
'data' => $data
|
|
]);
|
|
}
|
|
|
|
/**
|
|
* 获取请求参数
|
|
* @param string $key 参数名
|
|
* @param mixed $default 默认值
|
|
* @return mixed
|
|
*/
|
|
protected function getParam($key, $default = null) {
|
|
return I($key, $default);
|
|
}
|
|
|
|
/**
|
|
* 验证必需参数
|
|
* @param array $params 参数列表
|
|
* @return bool
|
|
*/
|
|
protected function validateParams($params) {
|
|
foreach ($params as $param) {
|
|
if (empty($this->getParam($param))) {
|
|
$this->error("参数 {$param} 不能为空");
|
|
return false;
|
|
}
|
|
}
|
|
return true;
|
|
}
|
|
} |