《PHP學習:php基于curl擴展制作跨平臺的restfule 接口》要點:
本文介紹了PHP學習:php基于curl擴展制作跨平臺的restfule 接口,希望對您有用。如果有疑問,可以聯系我們。
PHP編程restfule 接口
適用的平臺:跨平臺
所依賴:curl擴展
git:https://git.oschina.net/anziguoer/restAPI
PHP編程ApiServer.php
PHP編程
<?php
/**
* @Author: yangyulong
* @Email : anziguoer@sina.com
* @Date: 2015-04-30 05:38:34
* @Last Modified by: yangyulong
* @Last Modified time: 2015-04-30 17:14:11
*/
class apiServer
{
/**
* 客戶端哀求的方式
* @var string
*/
private $method = '';
/**
* 客戶端發送的數據
* @var [type]
*/
protected $param;
/**
* 要操作的資源
* @var [type]
*/
protected $resourse;
/**
* 要操作的資源id
* @var [type]
*/
protected $resourseId;
/**
* 構造函數, 獲取client 哀求的方式,以及傳輸的數據
* @param object 可以自定義傳入的對象
*/
public function __construct()
{
//首先對客戶端的哀求進行驗證
$this->authorization();
$this->method = strtolower($_SERVER['REQUEST_METHOD']);
//所有的哀求都是pathinfo模式
$pathinfo = $_SERVER['PATH_INFO'];
//將pathinfo數據信息映射為實際哀求方法
$this->getResourse($pathinfo);
//獲取傳輸的具體參數
$this->getData();
//執行響應
$this->doResponse();
}
/**
* 根據不同的哀求方式,獲取數據
* @return [type]
*/
private function doResponse(){
switch ($this->method) {
case 'get':
$this->_get();
break;
case 'post':
$this->_post();
break;
case 'delete':
$this->_delete();
break;
case 'put':
$this->_put();
break;
default:
$this->_get();
break;
}
}
// 將pathinfo數據信息映射為實際哀求方法
private function getResourse($pathinfo){
/**
* 將pathinfo數據信息映射為實際哀求方法
* GET /users: 逐頁列出所有用戶;
* POST /users: 創建一個新用戶;
* GET /users/123: 返回用戶為123的詳細信息;
* PUT /users/123: 更新用戶123;
* DELETE /users/123: 刪除用戶123;
*
* 根據以上規則,將pathinfo第一個參數映射為需要操作的數據表,
* 第二個參數映射為操作的id
*/
$info = explode('/', ltrim($pathinfo, '/'));
list($this->resourse, $this->resourseId) = $info;
}
/**
* 驗證哀求
*/
private function authorization(){
$token = $_SERVER['HTTP_CLIENT_TOKEN'];
$authorization = md5(substr(md5($token), 8, 24).$token);
if($authorization != $_SERVER['HTTP_CLIENT_CODE']){
//驗證失敗,輸出錯誤信息給客戶端
$this->outPut($status = 1);
}
}
/**
* [getData 獲取傳送的參數信息]
* @param [type] $pad [description]
* @return [type] [description]
*/
private function getData(){
//所有的參數都是get傳參
$this->param = $_GET;
}
/**
* 獲取資源操作
* @return [type] [description]
*/
protected function _get(){
//邏輯代碼根據自己實際項目需要實現
}
/**
* 新增資源操作
* @return [type] [description]
*/
protected function _post(){
//邏輯代碼根據自己實際項目需要實現
}
/**
* 刪除資源操作
* @return [type] [description]
*/
protected function _delete(){
//邏輯代碼根據自己實際項目需要實現
}
/**
* 更新資源操作
* @return [type] [description]
*/
protected function _put(){
//邏輯代碼根據自己實際項目需要實現
}
/**
* 出入服務端返回的數據信息 json格式
*/
public function outPut($stat, $data=array()){
$status = array(
//0 狀態表示哀求成功
0 => array(
'code' => 1,
'info' => '哀求成功',
'data' =>$data
),
//驗證失敗
1 => array(
'code' => 0,
'info' => '哀求不合法'
)
);
try{
if(!in_array($stat, array_keys($status))){
throw new Exception('輸入的狀態碼不合法');
}else{
echo json_encode($status[$stat]);
}
}catch (Exception $e){
die($e->getMessage());
}
}
}
PHP編程ApiClient.php
PHP編程
<?php
/**
* Created by PhpStorm.
* User: anziguoer@sina.com
* Date: 2015/4/29
* Time: 12:36
* link: http://www.ruanyifeng.com/blog/2014/05/restful_api.html [restful設計指南]
*/
/*** * * * * * * * * * * * * * * * * * * * * * * * * * ***\
* 定義路由的哀求方式 *
* *
* $url_model=0 *
* 采用傳統的URL參數模式 *
* http://serverName/appName/?m=module&a=action&id=1 *
* * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* PATHINFO模式(默認模式) *
* 設置url_model 為1 *
* http://serverName/appName/module/action/id/1/ *
** * * * * * * * * * * * * * * * * * * * * * * * * * * **
*/
class restClient
{
//哀求的token
const token='yangyulong';
//哀求url
private $url;
//哀求的類型
private $requestType;
//哀求的數據
private $data;
//curl實例
private $curl;
public $status;
private $headers = array();
/**
* [__construct 構造方法, 初始化數據]
* @param [type] $url 哀求的服務器地址
* @param [type] $requestType 發送哀求的方法
* @param [type] $data 發送的數據
* @param integer $url_model 路由哀求方式
*/
public function __construct($url, $data = array(), $requestType = 'get') {
//url是必須要傳的,并且是符合PATHINFO模式的路徑
if (!$url) {
return false;
}
$this->requestType = strtolower($requestType);
$paramUrl = '';
// PATHINFO模式
if (!empty($data)) {
foreach ($data as $key => $value) {
$paramUrl.= $key . '=' . $value.'&';
}
$url = $url .'?'. $paramUrl;
}
//初始化類中的數據
$this->url = $url;
$this->data = $data;
try{
if(!$this->curl = curl_init()){
throw new Exception('curl初始化錯誤:');
};
}catch (Exception $e){
echo '<pre>';
print_r($e->getMessage());
echo '</pre>';
}
curl_setopt($this->curl, CURLOPT_URL, $this->url);
curl_setopt($this->curl, CURLOPT_RETURNTRANSFER, 1);
}
/**
* [_post 設置get哀求的參數]
* @return [type] [description]
*/
public function _get() {
}
/**
* [_post 設置post哀求的參數]
* post 新增資源
* @return [type] [description]
*/
public function _post() {
curl_setopt($this->curl, CURLOPT_POST, 1);
curl_setopt($this->curl, CURLOPT_POSTFIELDS, $this->data);
}
/**
* [_put 設置put哀求]
* put 更新資源
* @return [type] [description]
*/
public function _put() {
curl_setopt($this->curl, CURLOPT_CUSTOMREQUEST, 'PUT');
}
/**
* [_delete 刪除資源]
* delete 刪除資源
* @return [type] [description]
*/
public function _delete() {
curl_setopt($this->curl, CURLOPT_CUSTOMREQUEST, 'DELETE');
}
/**
* [doRequest 執行發送哀求]
* @return [type] [description]
*/
public function doRequest() {
//發送給服務端驗證信息
if((null !== self::token) && self::token){
$this->headers = array(
'Client_Token: '.self::token,
'Client_Code: '.$this->setAuthorization()
);
}
//發送頭部信息
$this->setHeader();
//發送哀求方式
switch ($this->requestType) {
case 'post':
$this->_post();
break;
case 'put':
$this->_put();
break;
case 'delete':
$this->_delete();
break;
default:
curl_setopt($this->curl, CURLOPT_HTTPGET, TRUE);
break;
}
//執行curl哀求
$info = curl_exec($this->curl);
//獲取curl執行狀態信息
$this->status = $this->getInfo();
return $info;
}
/**
* 設置發送的頭部信息
*/
private function setHeader(){
curl_setopt($this->curl, CURLOPT_HTTPHEADER, $this->headers);
}
/**
* 生成授權碼
* @return string 授權碼
*/
private function setAuthorization(){
$authorization = md5(substr(md5(self::token), 8, 24).self::token);
return $authorization;
}
/**
* 獲取curl中的狀態信息
*/
public function getInfo(){
return curl_getinfo($this->curl);
}
/**
* 關閉curl連接
*/
public function __destruct(){
curl_close($this->curl);
}
}
PHP編程testClient.php
PHP編程
<?php
/**
* Created by PhpStorm.
* User: anziguoer@sina.com
* Date: 2015/4/29
* Time: 12:35
*/
include './ApiClient.php';
$arr = array(
'user' => 'anziguoer',
'passwd' => 'yangyulong'
);
// $url = 'http://localhost/restAPI/restServer.php';
$url = 'http://localhost/restAPI/testServer.php/user/123';
$rest = new restClient($url, $arr, 'get');
$info = $rest->doRequest();
//獲取curl中的狀態信息
$status = $rest->status;
echo '<pre>';
print_r($info);
echo '</pre>';
PHP編程testServer.php
PHP編程 <?php /** * @Author: anziguoer@sina.com * @Email: anziguoer@sina.com * @link: https://git.oschina.net/anziguoer * @Date: 2015-04-30 16:52:53 * @Last Modified by: yangyulong * @Last Modified time: 2015-04-30 17:26:37 */ include './ApiServer.php'; class testServer extends apiServer { /** * 先執行apiServer中的辦法,初始化數據 * @param object $obj 可以傳入的全局對象[數據庫對象,框架全局對象等] */ private $obj; function __construct()//object $obj { parent::__construct(); //$this->obj = $obj; //$this->resourse; 父類中已經實現,此類中可以直接使用 //$tihs->resourseId; 父類中已經實現,此類中可以直接使用 } /** * 獲取資源操作 * @return [type] [description] */ protected function _get(){ echo "get"; //邏輯代碼根據自己實際項目需要實現 } /** * 新增資源操作 * @return [type] [description] */ protected function _post(){ echo "post"; //邏輯代碼根據自己實際項目需要實現 } /** * 刪除資源操作 * @return [type] [description] */ protected function _delete(){ //邏輯代碼根據自己實際項目需要實現 } /** * 更新資源操作 * @return [type] [description] */ protected function _put(){ echo "put"; //邏輯代碼根據自己實際項目需要實現 } } $server = new testServer();
PHP編程以上所述就是本文的全部內容了,希望大家能夠喜歡.
歡迎參與《PHP學習:php基于curl擴展制作跨平臺的restfule 接口》討論,分享您的想法,維易PHP學院為您提供專業教程。