1. 程式人生 > >使用Slim PHP Framework建立基於令牌的RESTful服務

使用Slim PHP Framework建立基於令牌的RESTful服務

<?php需要  ' db.php '; 要求 ' Slim / Slim.php ';  \ Slim \ Slim :: registerAutoloader();  $ app = new \ Slim \ Slim();  $ APP->的get( '/為userDetails', 'getUserDetails');  $ APP->的get( '/使用者', 'getUsers');  $ APP->交的( '/ userUpdates', 'userUpdates');  $ app-> post('/ insertUpdate','insertUpdate');  $ APP->刪除( '/更新/刪除/:UPDATE_ID /:USER_ID /:apiKey', 'deleteUpdate');  $ APP->的get( '/使用者/搜尋/:查詢', 'getUserSearch');  $ app-> run
(); //獲取http://www.yourwebsite。 .....  } 功能 userUpdates() {  $ =請求\苗條\苗條:: 的getInstance() - > 請求();  $ update = json_decode($ request-> getBody());  $ apiKey = $最新情況:> apiKey;  $ sever_apiKey = apiKey($ update-> user_id);  $ sql =“ SELECT A.user_id,A.username,A.name,A.profile_pic,B.update_id,B.user_update,B.created FROM users A,更新B WHERE A.user_id = B.user_id_fk ORDER BY B. update_id DESC
 “; try {  if($ apiKey == $ sever_apiKey) {  $ db = getDB(); $ stmt = $ db-> prepare($ sql);  $ stmt-> execute();  $ updates = $ stmt-> fetchAll(PDO :: FETCH_OBJ);  $ db = null ; echo ' {“updates”: '。json_encode($ updates)。' } ';  }  } 趕上PDOException $ E){ 回聲 ' { “錯誤”:{ “文”: '。$ e-> getMessage
()。'}}';  }  } 功能 getUserUpdate($ UPDATE_ID){  .....  ..... (){  $ request = \ Slim \ Slim :: getInstance() - > request();  $ update =  json_decode($ request-> getBody());  $ apiKey = $最新情況:> apiKey;  $ sever_apiKey = apiKey($ update-> user_id);  $ sql =“ INSERT INTO updates(user_update,user_id_fk,created,ip)VALUES(:user_update,:user_id ,:created ,:ip  ”; try {  if($ apiKey == $ sever_apiKey) {  $ db = getDB();  $ stmt = $ db-> prepare($ sql);  $ stmt->bindParam(“user_update”,$ update-> user_update);  $ stmt-> bindParam(“user_id”,$ update-> user_id);  $ time = time();  $ stmt-> bindParam(“created”,$ time);  $ ip = $ _SERVER ['REMOTE_ADDR'];  $ stmt-> bindParam(“ip”,$ ip);  $ stmt-> execute();  $ update-> id = $ db-> lastInsertId();  $ db = null;  $ update_id = $ update-> id; getUserUpdate($ update_id);  }  } 趕上PDOException  $ E){ 回聲  “ {”getMessage()。'}}';  }  } 函式deleteUpdate($ UPDATE_ID,$ USER_ID,$ apiKey) {  $ sever_apiKey = apiKey($ USER_ID);  $ sql =“ DELETE FROM api_updates WHERE update_id =:update_id ”;  try {  if($ apiKey == $ sever_apiKey) {  $ db = getDB();  $ stmt = $ db-> prepare($ sql);  $ stmt-> bindParam(“update_id”,$ update_id);  $ stmt->執行();  $ db = null;  回聲真實;  }  } 趕上PDOException  $ E){ 回聲 ' {“error”:{“text”: '。$ e-> getMessage()。'}}';  }  }  功能  getUserUpdate($ UPDATE_ID){ // ...... // ......// GET http://www.yourwebsite.com/api/users/search/sri 功能getUserSearch($查詢) { // ..... // ....?>