Thinkphp接口公共類(最基本的實現)

給初學者的參考: 

<?php
/**
 *
 * @authors dl
 * @date    2018-11-24 11:19:59
 * @version $Id$
 */
namespace app\api\controller;
use think\Controller;
use think\Request;
use think\Validate;

class Common extends Controller {
    protected $request;
    protected $validater;
    protected $params;
    protected $rules = [
        'Test' => [
            'test1' => [
                ['email', 'require|email'],
                ['user_name', 'require|chsDash|max:30', '用戶名稱必須輸入|用戶名稱格式錯誤|用戶名稱最大不能超過30'],
                ['password', 'require|length:32', '密碼不能爲空|密碼格式錯誤'],
            ],
            'test2' => [
                'user_name' => 'require|chsDash|max:30',
                'password' => 'require|length:32',
            ],
        ],
    ];

    protected function _initialize() {
        $this->request = Request::instance();
        $this->check_time($this->request->only(['time'])); //時間驗證
        $this->check_token($this->request->param()); //token驗證
        $this->params = $this->check_params($this->request->except(['time'])); //參數驗證
    }
    /**
     * 驗證請求是否超時
     * @param  string $arr [包含時間戳的參數數組]
     * @return [json]      [檢測結果]
     */
    public function check_time($arr = []) {
        $time = intval($arr['time']);
        if (!isset($arr['time']) || $time <= 1) {
            $this->return_msg(400, '時間戳不存在');
        }
        if (time() - $time > 60) {
            $this->return_msg(400, '請求超時');
        }
    }
    /**
     * 驗證token(暫時用對稱加密簡單驗證下)
     * @param  array  $arr [description]
     * @return [type]      [description]
     */
    public function check_token($arr = []) {
        /***** api傳過來的token *****/
        if (!isset($arr['token']) || empty($arr['token'])) {
            $this->return_msg(400, 'token值不能爲空');
        }
        $api_token = $arr['token'];
        unset($arr['token']);
        /***** 服務端生成token *****/
        $service_token = '';
        foreach ($arr as $key => $value) {
            $service_token .= md5($value);
        }
        $service_token = md5('api_' . $service_token . '_api');
        /***** 對比token,返回結果 *****/
        if ($api_token !== $service_token) {
            $this->return_msg(400, 'token值不正確');
        }
    }
    /**
     * 驗證參數,參數過濾
     * @param  array  $arr [除time之外的所有參賽]
     * @return [return]      [合格的參數輸入]
     */
    public function check_params($arr = []) {
        /***** 獲取驗證規則 *****/
        $rule = $this->rules[$this->request->controller()][$this->request->action()];
        /***** 驗證參數並返回錯誤 *****/
        $this->validater = new Validate($rule);
        if (!$this->validater->check($arr)) {
            $this->return_msg(400, $this->validater->getError());
        }
        /***** 如果正常,通過驗證 *****/
        return $arr;
    }
    /**
     * json返回,返回值過濾null
     * @param  [int] $code [結果碼]
     * @param  [strstring] $msg  [錯誤信息]
     * @param  array  $data [接口要返回的數據]
     * @return [json]       [最終的json數據]
     */
    public function return_msg($code, $msg = '', $data = []) {
        $result = [
            'code' => $code,
            'msg' => $msg,
            'data' => $data,
        ];
        // array_walk_recursive($result, function (& $val, $key ) { if ($val === null)  $val = ''; });//過濾null值
        $result = json_encode($result, JSON_UNESCAPED_UNICODE);
        $result = str_replace('null', '""', $result);
        die($result);
    }
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章