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
<? 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.