Php creates a cross-platform restfule interface based on curl extension. phpcurlrestfule_PHP tutorial

Source: Internet
Author: User
Php creates a cross-platform restfule interface based on curl extension, phpcurlrestfule. Php creates cross-platform restfule interfaces based on curl extensions. applicable platforms for phpcurlrestfulerestfule interfaces: cross-platform dependency: curl extension git: git. oschina. netanziguoerre php creates cross-platform restfule interfaces based on curl extensions.

Restfule interface
Applicable platform: cross-platform
Dependent on: curl extension
Git: https://git.oschina.net/anziguoer/restAPI

ApiServer. php

<? Php/*** @ Author: yangyulong * @ Email: anziguoer@sina.com * @ Date: 05:38:34 * @ Last Modified by: yangyulong * @ Last Modified time: 17:14:11 */class apiServer {/*** method of client request * @ var string */private $ method = ''; /*** data sent by the client * @ var [type] */protected $ param;/*** resource to be operated ** @ var [type] */protected $ resourse; /*** resource id to be operated * @ var [type] */protected $ resourseId;/*** structure Function, obtain the client request method, and transmit data * @ param object can customize the input object */public function _ construct () {// verify the client REQUEST first $ this-> authorization (); $ this-> method = strtolower ($ _ SERVER ['request _ method']); // all requests are in the pathinfo mode $ pathinfo = $ _ SERVER ['path _ info']; // map the pathinfo data information to the actual request method $ this-> getResourse ($ pathinfo); // Obtain the specific transmission parameter $ this-> getData (); // execute the response $ this-> doResponse ();}/*** get data according to different request methods * @ return [type] */pri Vate 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 ;}} // map the pathinfo data information to the actual request method private function getResourse ($ pathinfo) {/*** map the pathinfo data information to the actual request method * GET/users: list all users page by page; * POST/users: create a new user; * GET/users/123: 1 is returned. * PUT/users/123: update user 123; * DELETE/users/123: DELETE user 123; ** According to the preceding rules, map the first parameter of pathinfo to the data table to be operated, and * the second parameter is mapped to the Operation id */$ 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, 24 ). $ token); if ($ authorization! = $ _ SERVER ['http _ CLIENT_CODE ']) {// The verification fails and an error message is outPut to the client $ this-> outPut ($ status = 1 );}} /*** [getData obtains the transmitted parameter information] * @ param [type] $ pad [description] * @ return [type] [description] */private function getData () {// All parameters are get passed parameters $ this-> param =$ _ GET ;} /*** obtain resource operation ** @ return [type] [description] */protected function _ get () {// logic code is implemented according to your actual project needs}/*** add resource operation * @ return [type] [description] */protected func Tion _ post () {// The logic code is implemented according to your actual project needs}/*** delete resource operation * @ return [type] [description] */protected function _ delete () {// logic code is implemented according to your actual project needs}/*** resource update operation * @ return [type] [description] */protected function _ put () {// The logic code is implemented according to your actual project requirements}/*** The json format of the data returned from and from the server */public function outPut ($ stat, $ data = array ()) {$ status = array (// 0 status indicates successful request 0 => array ('code' => 1, 'info' => 'successful request ', 'data' => $ data), // verification failed 1 => array ('code' => 0, 'info' => 'request illegal '); try {if (! In_array ($ stat, array_keys ($ status) {throw new Exception ('Invalid input status code ');} else {echo json_encode ($ status [$ stat]) ;}} catch (Exception $ e) {die ($ e-> getMessage ());}}}

ApiClient. php

<? Php/*** Created by PhpStorm. * User: anziguoer@sina.com * Date: * Time: * link: http://www.ruanyifeng.com/blog/2014/05/restful_api.html [Restful design guide] * // ****************************** \ * define the route request method ***** $ url_model = 0 ** using the traditional URL parameter mode ** http://serverName/appName/?m=module&a=action&id=1 * ****************************** PATHINFO mode (default mode) ** set url_model to 1 ** http://serverName/appName/module/action/id/1/ * *****************************/Class restClient {// requested token const token = 'yanglong '; // request url private $ url; // request type private $ requestType; // request data private $ data; // curl instance private $ curl; public $ status; private $ headers = array ();/*** [_ construct constructor, initialize data] * @ param [type] $ server address of the url request * @ param [type] $ requestType method of sending the request * @ param [type] $ data sent *@ param intege R $ url_model route request method */public function _ construct ($ url, $ data = array (), $ requestType = 'get ') {// The url must be passed and is the path in 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;} // data in the initialization class $ this-> url = $ url; $ this-> data = $ data; try {if (! $ This-> curl = curl_init () {throw new Exception ('curl initialization error: ') ;};} 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 setting get request parameters] * @ return [type] [description] */public function _ get () {}/*** [_ post setting post request parameters] * add post 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 resource] * delete resource * @ return [type] [description] */public function _ delete () {curl_setopt ($ this-> curl, CURLOPT_CUSTOMREQUEST, 'delete ');} /*** [send a request to doRequest] * @ return [type] [description] */public function doRequest () {// send it to the server If (null! = Self: token) & self: token) {$ this-> headers = array ('Client _ Token :'. self: token, 'Client _ Code :'. $ this-> setAuthorization ();} // sends the header information $ this-> setHeader (); // sends the request method 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); // Obtain the curl execution status information $ this-> status = $ this-> getInfo (); return $ info;}/*** set the sending header information */private function setHeader () {curl_setopt ($ this-> curl, CURLOPT_HTTPHEADER, $ this-> headers );} /*** generate authorization code * @ return string authorization code */private function setAuthorization () {$ authorization = md5 (substr (md5 (self: token), 8, 24 ). self: token); return $ authorization;}/*** get status information in curl */public function getInfo () {return curl_getinfo ($ this-> curl );} /*** close the curl Connection */public function _ destruct () {curl_close ($ this-> curl );}}

TestClient. php

<? Php/*** Created by PhpStorm. * User: anziguoer@sina.com * Date: * Time: */include '. /ApiClient. php '; $ arr = array ('user' => 'anziguoer', 'passwd' => 'yanglong'); // $ url = 'http: // localhost/restAPI/restServer. php '; $ url = 'http: // localhost/restAPI/testServer. php/user/100'; $ rest = new restClient ($ url, $ arr, 'Get'); $ info = $ rest-> doRequest (); // obtain the status information in 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: 16:52:53 * @ Last Modified by: yangyulong * @ Last Modified time: 17:26:37 */include '. /ApiServer. php '; class testServer extends apiServer {/*** first executes the method in apiServer to initialize data * @ param object $ obj: a global object that can be passed in [Database object, frame global object] */private $ obj; function _ construct () // object $ obj {parent :__ construct (); // $ this-> obj = $ obj; // $ this-> resourse; implemented in the parent class, which can be directly used // $ tihs-> resourseId; implemented in the parent class, which can be directly used}/*** obtain resource operation * @ return [type] [description] */protected function _ get () {echo "get "; // the logic code is implemented according to your actual project needs.}/*** add resource operation * @ return [type] [description] */protected function _ post () {echo "post "; // the logic code is implemented according to your actual project requirements.}/*** delete resource operation * @ return [type] [description] */protected function _ delete () {// logic code is implemented according to your actual project needs}/*** resource update operation * @ return [type] [description] */protected function _ put () {echo "put"; // The logic code is implemented according to your actual project needs.} $ server = new testServer ();

The above is all the content of this article. I hope you will like it.

Platform Interface, phpcurlrestfule restfule interface applicable platform: cross-platform dependency: curl extension git: https://git.oschina.net/anziguoer/re...

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.