PHP Restfule Interface _php instance based on Curl extension

Source: Internet
Author: User
Tags curl getmessage md5

Restfule interface
Platform for application: Cross-platform
Dependent on: 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:
  Yangyulong * @Last Modified time:2015-04-30 17:14:11/class Apiserver {/** * Client Requested method * @var String * *
 
  Private $method = ';
 
  /** * The data sent by the client * @var [Type] * * * protected $param;
 
  /** * The resource to be manipulated * @var [type] */protected $resourse;
 
 
  /** * The resource ID to be manipulated * @var [type] */protected $resourseId; /** * constructor, get the way of client request, and transmit data * @param object can customize incoming object/Public function __construct () {//First to Client
 
    The request is validated $this->authorization ();
 
    $this->method = strtolower ($_server[' Request_method '));
 
    All requests are pathinfo mode $pathinfo = $_server[' path_info '];
 
    The PathInfo data information is mapped into the actual request method $this->getresourse ($pathinfo);
 
    Obtain the specific parameters of the transmission $this->getdata ();
  Execute response $this->doresponse (); /** * Gets the data * @return [type]/private function doRe according to different request methodsSponse () {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
     The PathInfo data information is mapped to the actual request method Private function Getresourse ($pathinfo) {/** * maps pathinfo data to the actual request method
     * Get/users: List all users by page; * Post/users: Create a new user; * get/users/123: Returns the user 123 detailed information;
     * put/users/123: Update user 123;
     * delete/users/123: Delete user 123; * * According to the above rules, the first parameter of PathInfo is mapped to the data table that needs to be manipulated, * The second parameter is mapped 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 transfer parameter information] * @param [Type] $pad [description] * @return [type] [description]/P
  rivate function GetData () {//All parameters are get arguments $this->param = $_get;  
 
  /** * Get resource operation * @return [type] [description]/protected function _get () {//logical code according to its actual project needs to implement} 
   /** * New Resource operations * @return [type] [description]/protected function _post () {//logical code implemented according to its actual project needs}/**
   * Delete Resource operation * @return [type] [description]/protected function _delete () {//logical code is implemented according to its actual project}/** * Update Resource operations * @return [type] [description]/protected function _put () {//logical code according to their actual project needs to implement}/** * Access to Clothing The data information returned by the service is JSON format/public function OutPut ($stat, $data =array ()) {$status = array (//0 status indicates the request succeeded 0 =&G T Array (' Code ' => 1, ' info ' => ' request success ', ' Data ' =&Gt; $data),//validation failed 1 => Array (' code ' => 0, ' info ' => ' request illegal '));
      try{if (!in_array ($stat, Array_keys ($status)) {throw new Exception (' Input status code 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.h * * $url _model=0 * * Using the traditional URL parameter mode * * Http://serverName/appNa  * * Set Url_model 1 * * * * * * * * * * * * * * * * * * * * * * * * *
   
  Request URL private $url;
   
  Type of request private $requestType;
   
  The requested data private $data;
 
  Curl Instance private $curl;
 
  Public $status;
  Private $headers = Array ();   /** * [__construct construction method, initialization data] * @param [type] $url  The requested server address * @param [type] $requestType the method of sending the request * @param [type] $data sent data * @param integer $url _model Routing requester Type */Public function __construct ($url, $data = Array (), $requestType = ' get ') {//url is required to be passed, and is in accordance with PathInfo mode
    The path 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;
     
    //Initialize data in class $this->url = $url;
    $this->data = $data;
      try{if (! $this->curl = Curl_init ()) {throw new Exception (' Curl initialization error: ');
    };
      }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 set parameters for GET requests] * @return [type] [description]/Public function _get () {}/** * [_post set POST request Parameters] * 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_setopt ($this->curl, curlopt_customrequest, ' put ');
    /** * [_delete Delete Resource] * Delete resource * @return [type] [description]/Public Function _delete () {
 
  curl_setopt ($this->curl, curlopt_customrequest, ' DELETE '); /** * [dorequest Execute send request] * @return [type] [description]/Public function dorequest () {//Sent to server-side validation Information if ((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
 
    //Execute Curl Request $info = curl_exec ($this->curl);
    Gets the Curl execution state information $this->status = $this->getinfo ();
  return $info; /** * SET Header message sent/Private function SetHeader () {curl_setopt ($this->curl, Curlopt_httpheader, $this-&
  Gt;headers); /** * Generate Authorization Code * @return String Authorization code */Private Function setauthorization () {$authorization = MD5 (substr (
    MD5 (Self::token), 8, Self::token);
  return $authorization;
  /** * Gets the status information in Curl/Public function getInfo () {return curl_getinfo ($this->curl); }/** * offClosed 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 ();
 
Gets the status information in the curl
$status = $rest->status;
Echo ' <pre> ';
Print_r ($info);
Echo ' </pre> ';

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/include '.
 
/apiserver.php ';
   Class TestServer extends Apiserver {/** * First executes the method in Apiserver, initializing data * @param object $obj Global objects that can be passed in (Database objects, framework global objects, etc.)
 
  * Private $obj;
    function __construct ()//object $obj {parent::__construct ();
    $this->obj = $obj; $this->resourse; is already implemented in the parent class and can be used directly in this class//$TIHS->resourseid; Implemented in the parent class, which can be used directly with the}/** * to obtain resource operations * @return [type] [description]/protected function _get () {echo
    "Get"; The logical code is implemented according to its actual project/** * New Resource operations * @return [type] [description]/protected function _post () {Ech
    O "POST"; The logical code is implemented according to its actual project needs}/** * Delete resource operations * @return [type] [description]/protected function _delete () {//Logos
 The code is based on its own actual project needs to implement}/**  * Update Resource operation * @return [type] [description]/protected function _put () {echo "put"; The logical code is implemented according to its own actual project} $server = new TestServer ();

The above is the entire contents of this article, I hope you can enjoy.

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.