現在前後端分離,就得用到接口,寫接口就得先定義好語言包,接口調用公共類.以下寫了一個post請求,數據格式是json方式,返回也是json數據
如圖postman
定義一個公共類和語言包
<?php require('L.php'); class AdminApiController { public function json($arr, $output = true) { $content = json_encode($arr, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES); if (! $output) { return $content; } // 跨域處理 $origin = isset($_SERVER['HTTP_ORIGIN']) ? $_SERVER['HTTP_ORIGIN'] : ''; $allow_origin = [ 'http://www.xxxxx.com',//生產環境 'http://www.test.com',//測試環境 ]; if (in_array($origin, $allow_origin)) { header('Access-Control-Allow-Origin: ' . $origin); } header('Content-Type: application/json; charset=utf-8'); exit($content); } /*** * add by wangming * 正確時返回 * @param $result * @param bool $output * @return string */ public function successResult($result, $output = true) { //$arr['data'] = $result; //$arr['code'] = 200; return $this->json($result, $output); } /*** * add by wangming * 出錯時返回方法 * @param $result * @param bool $output * @return string */ public function errorResult($result, $output = true) { $arr = []; if (is_numeric($result)) { $arr['code'] = intval($result); $arr['msg'] = L::t($result); }elseif (is_array($result)) { $arr = $result; } if (!isset($arr['code'])) { $arr['code'] = intval(ErrorCode::UNKNOWN_ERROR_TYPE); $arr['msg'] = is_string($result)?$result:L::t(ErrorCode::UNKNOWN_ERROR_TYPE); } return $this->json($arr, $output); } /** * POST提交數據 * @param $fields string|array raw|form-data * @param $header array HTTP頭 * @param $timeout integer 服務端處理超時(秒) * @return mixed */ public function curlPost($url, $fields = '', $header = ['Content-Type: application/json; charset=utf-8'], $timeout = 3) { $ch = curl_init(); curl_setopt($ch, CURLOPT_HTTPHEADER, $header); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_POSTFIELDS, $fields); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_TIMEOUT, $timeout); $data = curl_exec($ch); curl_close($ch); return $data; } } ?>
L.php
<?php /** * $Author: wolf * 提示返回碼 * $Id: L.php 17217 2019-04-06 10:29:00 */ class L { private static $dictionary = [ 10000 => '正常輸出', 10001 => '數據格式錯誤', 10002 => '參數access_token不能爲空', 10003 => '無效的access_token', 10004 => '過期的access_token', 10005 => 'token缺失或者錯誤', 10006 => 'token失效', 10007 => 'refresh token錯誤', 10008 => '過期的refresh_token', 10009 => '數據插入失敗', 10010 => '數據更新失敗', 10011 => '數據刪除失敗', 10012 => '參數類型錯誤', 10013 => '參數user_account不能爲空', 10014 => '接口解析出錯' ]; public static function t($code) { return isset(self::$dictionary[$code])?self::$dictionary[$code]:$code; } public function __invoke($code) { return isset(self::$dictionary[$code]) ? self::$dictionary[$code] : $code; } } ?>
請指導,學習架構師之路