RESTful
什么是RESTful接口呢?這里引幾個文章,可以先行閱讀
我們?yōu)槭裁匆肦ESTful
- 因為我們實現(xiàn)完全的前后端分離,需要一個接口規(guī)范,來方便和規(guī)范我們的接口規(guī)范
Try it!
這里我們實現(xiàn)一個登陸換取TOKEN的例子
- 首先我們新建一個控制
AuthController,注意這個控制器,需要繼承RestController
namespace V1\Controller;
use Think\Controller\RestController;//use Rest的控制器
class AuthController extends RestController //繼承Rest控制器
{
//protected $allowMethod = array('get','post','put','delete'); // REST允許的請求類型列表
//protected $allowType = array('json','html'); // REST允許請求的資源類型列表
public function index(){
}
}
- 然后我們寫一個方法,這里官方文檔說:
image.png
于是我們就可以新建一個方法login_post
public function login_post(){
echo "test";
//TODO
}
- 然后我們用工具測試一下,我們是否能請求到這個方法,這里我用的是Google Chrome的一個插件,叫做
Restlet Client
image.png
注意這里都是POST請求
- 成功的輸出了test,說明我們可以請求到這個接口。那么我們就可以寫一些業(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三個參數(shù),然后首先驗證參數(shù)是完整,然后驗證時間戳是否過期,然后鏈接數(shù)據(jù)庫驗證賬號,然后保存生成token并保存在Redis里,然后返回token和過期時間。
- 然后我們驗證一下

參數(shù)不全

時間戳過期

參數(shù)錯誤

正常返回
結(jié)束
var author = {
name:'丁波',
GitHub:'dingbo1028',
University:'BNUZ'
}

