requestType = Request::method(); // 控制器初始化 $this->_initialize(); // 跨域请求检测 $this->_checkCors(); } /** * 初始化操作 */ protected function _initialize() { // 初始化操作 } /** * 跨域检测 */ protected function _checkCors() { // 允许跨域 header('Access-Control-Allow-Origin: *'); header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS'); header('Access-Control-Allow-Headers: Authorization, Content-Type, If-Match, If-Modified-Since, If-None-Match, If-Unmodified-Since, X-Requested-With, X-Token, X-Api-Token'); header('Access-Control-Max-Age: 1728000'); header('Access-Control-Allow-Credentials: true'); // 对OPTIONS请求直接返回 if ($this->requestType === 'OPTIONS') { Response::create()->send(); exit; } } /** * 操作成功返回的数据 * @param string $msg 提示信息 * @param mixed $data 返回的数据 * @param int $code 错误码,默认为1 * @param string $type 输出类型 * @param array $header 发送的header信息 */ protected function success($msg = '', $data = null, $code = 1, $type = null, array $header = []) { $this->result($msg, $data, $code, $type, $header); } /** * 操作失败返回的数据 * @param string $msg 提示信息 * @param mixed $data 返回的数据 * @param int $code 错误码,默认为0 * @param string $type 输出类型 * @param array $header 发送的header信息 */ protected function error($msg = '', $data = null, $code = 0, $type = null, array $header = []) { $this->result($msg, $data, $code, $type, $header); } /** * 返回封装后的API数据 * @param string $msg 提示信息 * @param mixed $data 要返回的数据 * @param int $code 错误码,默认为0 * @param string $type 输出类型,支持json/xml/jsonp * @param array $header 发送的header信息 */ protected function result($msg, $data = null, $code = 0, $type = null, array $header = []) { $result = [ 'code' => $code, 'msg' => $msg, 'time' => time(), 'data' => $data, ]; // 返回数据格式 $type = $type ?: $this->responseType; // 发送响应 $response = Response::create($result, $type)->header($header); $response->send(); exit; } }