ThinkPHP5.0 API开发前进行配置路由和参数过滤

在被最新版TP5.1完虐了几天后,踩坑踩得都心情好几天都不好了。所以 决定放弃最新版,采用相对稳定版TP5.0.10版本进行 Restful API 开发:

1. 在进行开发前最需要得做的是配置本地域名,以及路由配置:

   (1)本地域名配置,前面得博文我已经讲过,这里就不再复述了;
   (2)这个版本路由配置,要比5.1版本要简单得多,直接在application目录下找到route.php文件,然后配置
 
     如下:

use think\Route;
// api.movi.com -> www.movi.com/index.php/api 
Route::domain('api', 'api');
// api.movi.com/user/login -> api.movi.com/user
Route::post('user', 'user/login');

2. 然后在application目录下,新建文件:
   (1) app/controller/Common.php
   (2) app/controller/User.php
   (3) app/controller/Article.php
   (4) ...

3. 验证过滤参数

  (1)验证请求时间是否过期(默认设置60s)
  (2)验证客户端传递过来得token是否与服务端得token是否匹配
  (3)验证客户端传递过来得其他参数是否格式正确(用户名,密码等)

4. 在其他控制器内部继承Common类;即可以在请求当前控制器方法时,进行过滤校验

 //User.php
namespace app\api\controller;

class User extends Common
{
    public function login()
    {
        $data = $this->params;

        dump($data);
    }
}


5. 模拟发出请求: api.movi.com/user ,响应结果为:

  array (size=2) 'user_name' => string 'asdadassad_ss'(length=13) 'user_pwd' => string 'adminss' (length=7)


6. 整个过滤的逻辑:

<?php

namespace app\api\controller;

use think\Controller;
use think\Request;
use think\Validate;

class Common extends Controller
{
    protected $req; //用来处理客户端传递过来的参数
    protected $validater; //用来验证数据/参数
    protected $params; //过滤后符合要求的参数

    //控制器下面方法所要接受参数的
    protected $rules = array(
        'User' => array(
            'login' => array(
                'user_name' => ['require', 'chsDash', 'max' => 20],
                'user_pwd' => ['require', 'max' => 16, 'min' => 6],
            ),
            'register' => array(),
        ),
    );

    protected function _initialize()
    {
        parent::_initialize();
        $this->req = Request::instance();

        //1. 检车请求时间是否超时
        $this->checkTime($this->req->only(['time']));

        //2. 验证token
        $this->checkToken($this->req->param());

        //3. 验证参数,返回成功过滤后的参数数组
        $this->params = $this->checkParams($this->req->except(['time', 'token']));
    }

    //检测请求的时间是否超时
    public function checkTime($arr)
    {
        //$this->returnMsg(400, '请求超时!');
        if (!isset($arr['time']) || intval($arr['time']) <= 1) {
            $this->returnMsg(400, '时间戳不存在!');
        }
        if (time() - intval($arr['time']) > 10) {
            $this->returnMsg(400, '请求超时!');
        }
    }

    //验证token方法 (防止篡改数据)
    /*
    $arr: 全部请求参数
    return : json
     */
    protected function checkToken($arr)
    {
        //检测客户端是否传递过来token数据
        if (!isset($arr['token']) || empty($arr['token'])) {
            $this->returnMsg(400, 'token不能为空');
        }

        //这是客户端api传递过来的token
        $app_token = $arr['token'];

        //如果已经传递token数据,就删除token数据,生成服务端token与客户端的token做对比
        unset($arr['token']);

        $session_token = '';
        foreach ($arr as $key => $val) {
            $session_token .= md5($val);
        }

        $session_token = md5('api_' . $session_token . '_api');

        //echo $session_token;die; //调试输出

        //如果传递过来的token不相等
        if ($app_token !== $session_token) {
            $this->returnMsg(400, 'token值不正确');
        }
    }

    //检测客户端传递过来的其他参数(用户名,其他相关)
    /*
    param: $arr [除了time,token以外的其他参数]
    return:     [合格的参数数组]
     */
    protected function checkParams($arr)
    {
        //1. 获取验证规则 (Array)
        $rule = $this->rules[$this->req->controller()][$this->req->action()];

        //2. 验证参数并且返回错误
        $this->validater = new Validate($rule);

        if (!$this->validater->check($arr)) {
            $this->returnMsg(400, $this->validater->getError());
        }

        //3. 如果正常,就通过验证

        return $arr;
    }

    //返回信息
    protected function returnMsg($code, $msg = '', $data = [])
    {
        $return_data['code'] = $code;
        $return_data['msg'] = $msg;
        $return_data['data'] = $data;

        echo json_encode($return_data);die;
    }
}

7.  验证过滤参数类Common.php源码:

     https://github.com/RiversCoder/tp5-api/blob/master/application/api/controller/Common.php

猜你喜欢

转载自blog.csdn.net/wu5229485/article/details/79681027
今日推荐