RESTful
什么是RESTful接口呢?這里引幾個(gè)文章,可以先行閱讀
- ThinkPHP3.2.3文檔REST
- 慕課網(wǎng) RESTful API實(shí)戰(zhàn)
- 理解RESTful架構(gòu)-阮一峰
- 一個(gè)網(wǎng)絡(luò)簡單的小例子
我們?yōu)槭裁匆肦ESTful
- 因?yàn)槲覀儗?shí)現(xiàn)完全的前后端分離,需要一個(gè)接口規(guī)范,來方便和規(guī)范我們的接口規(guī)范
Try it!
這里我們實(shí)現(xiàn)一個(gè)登陸換取TOKEN的例子
- 首先我們新建一個(gè)控制
AuthController
,注意這個(gè)控制器,需要繼承RestController
namespace V1\Controller;
use Think\Controller\RestController;//use Rest的控制器
class AuthController extends RestController //繼承Rest控制器
{
//protected $allowMethod = array('get','post','put','delete'); // REST允許的請(qǐng)求類型列表
//protected $allowType = array('json','html'); // REST允許請(qǐng)求的資源類型列表
public function index(){
}
}
- 然后我們寫一個(gè)方法,這里官方文檔說:
image.png
于是我們就可以新建一個(gè)方法login_post
public function login_post(){
echo "test";
//TODO
}
- 然后我們用工具測(cè)試一下,我們是否能請(qǐng)求到這個(gè)方法,這里我用的是Google Chrome的一個(gè)插件,叫做
Restlet Client
image.png
注意這里都是POST請(qǐng)求
- 成功的輸出了test,說明我們可以請(qǐng)求到這個(gè)接口。那么我們就可以寫一些業(yè)務(wù)代碼了:
private $res=array(
'code'=>200,
'msg'=>'ok',
'data'=>array()
);
public function login_post(){
$uuid = $_POST['uuid'];
$open = $_POST['open'];
$timestamp = $_POST['timestamp'];
if ($uuid==''||$open==''||$timestamp==''){
$this->res['code']=401;
$this->res['msg']='Incomplete parameters';
$this->response($this->res,"json");
exit();
}
$now = time();
if ($now-$timestamp>3600){
$this->res['code']=401;
$this->res['msg']='Login Timeout';
$this->response($this->res,"json");
exit();
}
$user = M('user');
$where['uuid']=$uuid;
$where['open']=$open;
$result = $user->where($where)->select();
if (empty($result)){
$this->res['code']=404;
$this->res['msg']='Invalid UserID or openid';
$this->response($this->res,'json');
exit();
}else{
$token = self::_applyTokenAndSaveInRedis($uuid,$open);
$this->res['data']=array(
'TOKEN'=>$token,
'Expiretime'=>3600
);
$this->response($this->res,'json');
}
}
private static function _applyTokenAndSaveInRedis($uuid,$open,$expiretime=3600){
$redis=new \Redis();
$redis->connect('地址','端口');
$redis->auth('密碼');
$s = rand(10000,99999);
$string = $open.$uuid.$s.time();
$token = md5($string);
$save = $token."*".(time()+$expiretime);
$redis->set($uuid,$save);
return $token;
}
這里的功能,是收取uuid
和open
和timestamp
三個(gè)參數(shù),然后首先驗(yàn)證參數(shù)是完整,然后驗(yàn)證時(shí)間戳是否過期,然后鏈接數(shù)據(jù)庫驗(yàn)證賬號(hào),然后保存生成token并保存在Redis里,然后返回token和過期時(shí)間。
- 然后我們驗(yàn)證一下
參數(shù)不全
時(shí)間戳過期
參數(shù)錯(cuò)誤
正常返回
結(jié)束
var author = {
name:'丁波',
GitHub:'dingbo1028',
University:'BNUZ'
}