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

Source: Internet
Author: User
This article mainly introduces the relevant information and detailed code for php to create a cross-platform restfule interface based on curl extension. For more information, see. Restfule interface
Applicable platform: cross-platform
Dependent on: curl extension
Git: https://git.oschina.net/anziguoer/restAPI

ApiServer. php

 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] */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 ;}// map pathinfo data to the actual request method private function getResourse ($ pathinfo) {/*** map pathinfo data to the actual request method * GET/users: list all users page by page; * POST/users: create a new user; * GET/users/123: returns the details of user 123; * PUT/users/123: updates user 123; * DELETE/users/123: deletes user 123; ** Based on the preceding rules, map the first parameter of pathinfo to the data table to be operated. * The second parameter is mapped. Is 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

 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

 '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

 Obj = $ obj; // $ this-> resourse; implemented in the parent class. you can use this class directly. // $ tihs-> resourseId; implemented in the parent class, this class can be used directly}/*** get 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 ();

For more articles about how to create cross-platform restfule interfaces based on curl extensions in php, refer to PHP Chinese network!

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.