php基於curl擴充製作跨平台的restfule 介面,phpcurlrestfule_PHP教程

來源:互聯網
上載者:User

php基於curl擴充製作跨平台的restfule 介面,phpcurlrestfule


restfule 介面
適用的平台:跨平台
所依賴:curl擴充
git:https://git.oschina.net/anziguoer/restAPI

ApiServer.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());    }  }}

ApiClient.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 '
';      print_r($e->getMessage());      echo '
'; } 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); }}

testClient.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 '
';print_r($info);echo '
';

testServer.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();

以上所述就是本文的全部內容了,希望大家能夠喜歡。

http://www.bkjia.com/PHPjc/997902.htmlwww.bkjia.comtruehttp://www.bkjia.com/PHPjc/997902.htmlTechArticlephp基於curl擴充製作跨平台的restfule 介面,phpcurlrestfule restfule 介面 適用的平台:跨平台 所依賴:curl擴充 git:https://git.oschina.net/anziguoer/re...

  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.