PHP build cross-platform Restfule interface _php instance based on Curl extension

Source: Internet
Author: User
Restfule interface
Applicable platforms: cross-platform
Dependent: Curl Extension
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:yangyu Long * @Last Modified time:2015-04-30 17:14:11 */class apiserver{/** * Client Request Way * @var String */Private $metho   d = ';   /** * The data sent by the client * @var [type] */protected $param;   /** * Resources to manipulate * @var [type] */protected $resourse;    /** * The resource ID to manipulate * @var [type] */protected $resourseId; /** * constructor that gets the way the client requests, as well as the data transferred * @param object can customize incoming objects */Public function __construct () {//) first check the client's request     Certificate $this->authorization ();     $this->method = strtolower ($_server[' request_method ');     All requests are pathinfo mode $pathinfo = $_server[' path_info ');     Map the PathInfo data information to the actual request method $this->getresourse ($pathinfo);     Get the specific parameters of the transmission $this->getdata ();  Execution Response $this->doresponse (); */** * @return [Type] */Private Function doresponse () {switch ($this->method) {CAs] According to different request methods        E ' get ':$this->_get ();      Break        Case ' post ': $this->_post ();      Break        Case ' delete ': $this->_delete ();      Break        Case ' put ': $this->_put ();      Break        Default: $this->_get ();    Break }}//Map PathInfo data information to the actual request method Private function Getresourse ($pathinfo) {/** * map pathinfo data information to the actual request method * GET     /users: List all users by page; * Post/users: Create a new user; * get/users/123: Returns the details of user 123;     * put/users/123: Update user 123;     * delete/users/123: Delete user 123;    * * According to the above rules, the pathinfo first parameter is mapped to the data table that needs operation, * the second parameter maps to the ID of the operation */$info = explode ('/', LTrim ($pathinfo, '/'));  List ($this->resourse, $this->resourseid) = $info;    }/** * Authentication request */Private Function authorization () {$token = $_server[' Http_client_token '];    $authorization = MD5 (SUBSTR (MD5 ($token), 8). $token);    if ($authorization! = $_server[' Http_client_code ')} {//validation failed, output error message to client $this->output ($status = 1);  }}/** * [GetData get transferred parameter information] * @param [Type] $pad [description] * @return [type] [description] */private Func  tion GetData () {//All parameters are GET parameter $this->param = $_get; }/** * Get resource operation * @return [type] [description] */protected function _get () {//logic code implemented according to your actual project}/** * New Resource Operation * @return [type] [description] */protected function _post () {//logic code according to its actual project need to implement}/** * Delete resource operation * @r Eturn [Type] [description] */protected function _delete () {//logic code according to its actual project needs to implement}/** * Update resource operation * @return [type ] [description] */protected function _put () {///logic code according to its actual project needs to implement}/** * Access data information returned by the server JSON format */public funct        Ion OutPut ($stat, $data =array ()) {$status = array (the//0 status indicates that the request succeeded 0 = = Array (' code ' = = 1,  ' Info ' = ' request succeeded ', ' data ' = ' $data ',//validation failed 1 = = Array (' Code ' = ' + 0 ', ' info ')     = ' request not lawful '); try{if (!in_array ($stat, Array_keys ($status))){throw new Exception (' The entered status code is not valid ');      }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.htm * * $url _model=0 * * Using the traditional URL parameter mode * * Http://serverName/appName/?m=mod  * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * ule&a=action&id=1 * * * * *  * Set Url_model to 1 * * http://serverName/appName/module/action/id/1/* * * * * * * * * * * * * * * * * * * *   * * * * * * * * * * * * * * * ***/class restclient{//Request Token const token= ' Yangyulong ';     Request URL private $url;     Type of request private $requestType;     The requested data is private $data;   Curl Instance private $curl;   Public $status;  Private $headers = Array (); /** * [__construct constructor method, initialize data] * @param [type] $url the requested server address * @param [type] $requestType sendRequested method * @param [type] $data sent data * @param integer $url _model route Request mode */Public function __construct ($url, $data    = Array (), $requestType = ' get ') {//url is a must-pass and is a path that conforms to PathInfo mode if (! $url) {return false;    } $this->requesttype = Strtolower ($requestType);    $PARAMURL = "; PathInfo mode if (!empty ($data)) {foreach ($data as $key = = $value) {$paramUrl. = $key. '=' . $value. '      & '; } $url = $url. '? '.    $PARAMURL;         }//Initializes the data in the class $this->url = $url;    $this->data = $data;      try{if (! $this->curl = Curl_init ()) {throw new Exception (' Curl initialization error: ');    }; }catch (Exception $e) {echo '
'; } curl_setopt ($this->curl, Curlopt_url, $this->url); curl_setopt ($this->curl, Curlopt_returntransfer, 1); }/** * [_post Set parameters for GET request] * @return [type] [description] */Public Function _get () {}/** * [_post settings Parameters for POST Request] * Post New resource * @return [type] [description] */Public Function _post () {curl_setopt ($this->curl, Curlopt_post, 1); curl_setopt ($this->curl, Curlopt_postfields, $this->data); }/** * [_put set put request] * put update resource * @return [type] [description] * * Public Function _put () {Curl_set Opt ($this->curl, curlopt_customrequest, ' PUT '); }/** * [_delete Delete Resource] * Delete Remove resource * @return [type] [description] * * Public Function _delete () {Curl_se Topt ($this->curl, curlopt_customrequest, ' DELETE '); }/** * [dorequest Execute send request] * @return [type] [description] */Public Function dorequest () {//Send to server authentication information I F ((null!== self::token) && self::token) {$this->headers = Array (' Client_token: '. Self::token, ' Client_code: '. $this->setauthorization ()); }//Send header information $this->setheader (); Send request mode 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 }//Perform curl Request $info = curl_exec ($this->curl); Gets the Curl execution status information $this->status = $this->getinfo (); return $info; /** * Set the header message to send */Private function SetHeader () {curl_setopt ($this->curl, Curlopt_httpheader, $this->hea DERs); }/** * Generate Authorization Code * @return String Authorization code */Private Function setauthorization () {$authorization = MD5 (SUBSTR (MD5 (SEL F::token), 8, Self::token); return $authorization; }/** * Get status information in curl */Public Function GetInfo () {return curl_GetInfo ($this->curl); }/** * Close Curl Connection */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 (); Get status information in curl $status = $rest->status;echo '
';p rint_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{/** * First executes the method in Apiserver, initializes the data * @param object $obj The global object that can be passed in [Database object, Framework global object, etc.] */   Private $obj;    function __construct ()//object $obj {parent::__construct ();    $this->obj = $obj; $this->resourse; The parent class is already implemented and can be used directly in this class//$TIHS->resourseid;    The parent class is already implemented and can be used directly in this class to get resource operations * @return [type] [description] */protected function _get () {echo "get"; Logic code according to the actual project needs to implement}/** * New resource operation * @return [type] [description] */protected function _post () {echo "pos    T "; Logic code according to the actual project needs to implement}/** * Delete resource operation * @return [type] [description] */protected function _delete () {//logic code according to its own real /** * Update Resource operations * @return [type] [description] */protected function _put () {echo "put"; Logic code is implemented according to its actual project}} $server = new TestServer ();

The above mentioned is the whole content of this article, I hope you can like.

  • Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    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.