当前位置:Gxlcms > PHP教程 > php基于curl扩展制作跨平台的restfule接口,phpcurlrestfule_PHP教程

php基于curl扩展制作跨平台的restfule接口,phpcurlrestfule_PHP教程

时间:2021-07-01 10:21:17 帮助过:25人阅读

php基于curl扩展制作跨平台的restfule 接口,phpcurlrestfule


restfule 接口
适用的平台:跨平台
所依赖:curl扩展
git:https://git.oschina.net/anziguoer/restAPI

ApiServer.php

  1. <?php
  2. /**
  3. * @Author: yangyulong
  4. * @Email : anziguoer@sina.com
  5. * @Date: 2015-04-30 05:38:34
  6. * @Last Modified by: yangyulong
  7. * @Last Modified time: 2015-04-30 17:14:11
  8. */
  9. class apiServer
  10. {
  11. /**
  12. * 客户端请求的方式
  13. * @var string
  14. */
  15. private $method = '';
  16. /**
  17. * 客户端发送的数据
  18. * @var [type]
  19. */
  20. protected $param;
  21. /**
  22. * 要操作的资源
  23. * @var [type]
  24. */
  25. protected $resourse;
  26. /**
  27. * 要操作的资源id
  28. * @var [type]
  29. */
  30. protected $resourseId;
  31. /**
  32. * 构造函数, 获取client 请求的方式,以及传输的数据
  33. * @param object 可以自定义传入的对象
  34. */
  35. public function __construct()
  36. {
  37. //首先对客户端的请求进行验证
  38. $this->authorization();
  39. $this->method = strtolower($_SERVER['REQUEST_METHOD']);
  40. //所有的请求都是pathinfo模式
  41. $pathinfo = $_SERVER['PATH_INFO'];
  42. //将pathinfo数据信息映射为实际请求方法
  43. $this->getResourse($pathinfo);
  44. //获取传输的具体参数
  45. $this->getData();
  46. //执行响应
  47. $this->doResponse();
  48. }
  49. /**
  50. * 根据不同的请求方式,获取数据
  51. * @return [type]
  52. */
  53. private function doResponse(){
  54. switch ($this->method) {
  55. case 'get':
  56. $this->_get();
  57. break;
  58. case 'post':
  59. $this->_post();
  60. break;
  61. case 'delete':
  62. $this->_delete();
  63. break;
  64. case 'put':
  65. $this->_put();
  66. break;
  67. default:
  68. $this->_get();
  69. break;
  70. }
  71. }
  72. // 将pathinfo数据信息映射为实际请求方法
  73. private function getResourse($pathinfo){
  74. /**
  75. * 将pathinfo数据信息映射为实际请求方法
  76. * GET /users: 逐页列出所有用户;
  77. * POST /users: 创建一个新用户;
  78. * GET /users/123: 返回用户为123的详细信息;
  79. * PUT /users/123: 更新用户123;
  80. * DELETE /users/123: 删除用户123;
  81. *
  82. * 根据以上规则,将pathinfo第一个参数映射为需要操作的数据表,
  83. * 第二个参数映射为操作的id
  84. */
  85. $info = explode('/', ltrim($pathinfo, '/'));
  86. list($this->resourse, $this->resourseId) = $info;
  87. }
  88. /**
  89. * 验证请求
  90. */
  91. private function authorization(){
  92. $token = $_SERVER['HTTP_CLIENT_TOKEN'];
  93. $authorization = md5(substr(md5($token), 8, 24).$token);
  94. if($authorization != $_SERVER['HTTP_CLIENT_CODE']){
  95. //验证失败,
输出错误信息给客户端 $this->outPut($status = 1); } } /** * [getData 获取传送的参数信息] * @param [type] $pad [description] * @return [type] [description] */ private function getData(){ //所有的参数都是get传参 $this->param = $_GET; } /** * 获取资源操作 * @return [type] [description] */ protected function _get(){ //逻辑代码根据自己实际项目需要实现 } /** * 新增资源操作 * @return [type] [description] */ protected function _post(){ //逻辑代码根据自己实际项目需要实现 } /** * 删除资源操作 * @return [type] [description] */ protected function _delete(){ //逻辑代码根据自己实际项目需要实现 } /** * 更新资源操作 * @return [type] [description] */ protected function _put(){ //逻辑代码根据自己实际项目需要实现 } /** * 出入服务端返回的数据信息 json格式 */ public function outPut($stat, $data=array()){ $status = array( //0 状态表示请求成功 0 => array( 'code' => 1, 'info' => '请求成功', 'data' =>$data ), //验证失败 1 => array( 'code' => 0, 'info' => '请求不合法' ) ); try{ if(!in_array($stat, array_keys($status))){ throw new Exception('输入的状态码不合法'); }else{ echo json_encode($status[$stat]); } }catch (Exception $e){ die($e->getMessage()); } } }

ApiClient.php

  1. <?php
  2. /**
  3. * Created by PhpStorm.
  4. * User: anziguoer@sina.com
  5. * Date: 2015/4/29
  6. * Time: 12:36
  7. * link: http://www.ruanyifeng.com/blog/2014/05/restful_api.html [restful设计指南]
  8. */
  9. /*** * * * * * * * * * * * * * * * * * * * * * * * * * ***\
  10. * 定义路由的请求方式 *
  11. * *
  12. * $url_model=0 *
  13. * 采用传统的URL参数模式 *
  14. * http://serverName/appName/?m=module&a=action&id=1 *
  15. * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
  16. * PATHINFO模式(默认模式) *
  17. * 设置url_model 为1 *
  18. * http://serverName/appName/module/action/id/1/ *
  19. ** * * * * * * * * * * * * * * * * * * * * * * * * * * **
  20. */
  21. class restClient
  22. {
  23. //请求的token
  24. const token='yangyulong';
  25. //请求url
  26. private $url;
  27. //请求的类型
  28. private $requestType;
  29. //请求的数据
  30. private $data;
  31. //curl实例
  32. private $curl;
  33. public $status;
  34. private $headers = array();
  35. /**
  36. * [__construct 构造方法, 初始化数据]
  37. * @param [type] $url 请求的服务器地址
  38. * @param [type] $requestType 发送请求的方法
  39. * @param [type] $data 发送的数据
  40. * @param integer $url_model 路由请求方式
  41. */
  42. public function __construct($url, $data = array(), $requestType = 'get') {
  43. //url是必须要传的,并且是符合PATHINFO模式的路径
  44. if (!$url) {
  45. return false;
  46. }
  47. $this->requestType = strtolower($requestType);
  48. $paramUrl = '';
  49. // PATHINFO模式
  50. if (!empty($data)) {
  51. foreach ($data as $key => $value) {
  52. $paramUrl.= $key . '=' . $value.'&';
  53. }
  54. $url = $url .'?'. $paramUrl;
  55. }
  56. //初始化类中的数据
  57. $this->url = $url;
  58. $this->data = $data;
  59. try{
  60. if(!$this->curl = curl_init()){
  61. throw new Exception('curl初始化错误:');
  62. };
  63. }catch (Exception $e){
  64. echo '<pre class="brush:php;toolbar:false layui-box layui-code-view layui-code-notepad"><ol class="layui-code-ol"><li>';</li><li> print_r($e->getMessage());</li><li> echo '</li></ol></pre>';
  65. }
  66. curl_setopt($this->curl, CURLOPT_URL, $this->url);
  67. curl_setopt($this->curl, CURLOPT_RETURNTRANSFER, 1);
  68. }
  69. /**
  70. * [_post 设置get请求的参数]
  71. * @return [type] [description]
  72. */
  73. public function _get() {
  74. }
  75. /**
  76. * [_post 设置post请求的参数]
  77. * post 新增资源
  78. * @return [type] [description]
  79. */
  80. public function _post() {
  81. curl_setopt($this->curl, CURLOPT_POST, 1);
  82. curl_setopt($this->curl, CURLOPT_POSTFIELDS, $this->data);
  83. }
  84. /**
  85. * [_put 设置put请求]
  86. * put 更新资源
  87. * @return [type] [description]
  88. */
  89. public function _put() {
  90. curl_setopt($this->curl, CURLOPT_CUSTOMREQUEST, 'PUT');
  91. }
  92. /**
  93. * [_delete 删除资源]
  94. * delete 删除资源
  95. * @return [type] [description]
  96. */
  97. public function _delete() {
  98. curl_setopt($this->curl, CURLOPT_CUSTOMREQUEST, 'DELETE');
  99. }
  100. /**
  101. * [doRequest 执行发送请求]
  102. * @return [type] [description]
  103. */
  104. public function doRequest() {
  105. //发送给服务端验证信息
  106. if((null !== self::token) && self::token){
  107. $this->headers = array(
  108. 'Client_Token: '.self::token,
  109. 'Client_Code: '.$this->setAuthorization()
  110. );
  111. }
  112. //发送头部信息
  113. $this->setHeader();
  114. //发送请求方式
  115. switch ($this->requestType) {
  116. case 'post':
  117. $this->_post();
  118. break;
  119. case 'put':
  120. $this->_put();
  121. break;
  122. case 'delete':
  123. $this->_delete();
  124. break;
  125. default:
  126. curl_setopt($this->curl, CURLOPT_HTTPGET, TRUE);
  127. break;
  128. }
  129. //执行curl请求
  130. $info = curl_exec($this->curl);
  131. //获取curl执行状态信息
  132. $this->status = $this->getInfo();
  133. return $info;
  134. }
  135. /**
  136. * 设置发送的头部信息
  137. */
  138. private function setHeader(){
  139. curl_setopt($this->curl, CURLOPT_HTTPHEADER, $this->headers);
  140. }
  141. /**
  142. * 生成授权码
  143. * @return string 授权码
  144. */
  145. private function setAuthorization(){
  146. $authorization = md5(substr(md5(self::token), 8, 24).self::token);
  147. return $authorization;
  148. }
  149. /**
  150. * 获取curl中的状态信息
  151. */
  152. public function getInfo(){
  153. return curl_getinfo($this->curl);
  154. }
  155. /**
  156. * 关闭curl连接
  157. */
  158. public function __destruct(){
  159. curl_close($this->curl);
  160. }
  161. }

testClient.php

  1. <?php
  2. /**
  3. * Created by PhpStorm.
  4. * User: anziguoer@sina.com
  5. * Date: 2015/4/29
  6. * Time: 12:35
  7. */
  8. include './ApiClient.php';
  9. $arr = array(
  10. 'user' => 'anziguoer',
  11. 'passwd' => 'yangyulong'
  12. );
  13. // $url = 'http://localhost/restAPI/restServer.php';
  14. $url = 'http://localhost/restAPI/testServer.php/user/123';
  15. $rest = new restClient($url, $arr, 'get');
  16. $info = $rest->doRequest();
  17. //获取curl中的状态信息
  18. $status = $rest->status;
  19. echo '<pre class="brush:php;toolbar:false layui-box layui-code-view layui-code-notepad"><ol class="layui-code-ol"><li>';</li><li>print_r($info);</li><li>echo '</li></ol></pre>';

testServer.php

  1. <?php
  2. /**
  3. * @Author: anziguoer@sina.com
  4. * @Email: anziguoer@sina.com
  5. * @link: https://git.oschina.net/anziguoer
  6. * @Date: 2015-04-30 16:52:53
  7. * @Last Modified by: yangyulong
  8. * @Last Modified time: 2015-04-30 17:26:37
  9. */
  10. include './ApiServer.php';
  11. class testServer extends apiServer
  12. {
  13. /**
  14. * 先执行apiServer中的方法,初始化数据
  15. * @param object $obj 可以传入的全局对象[数据库对象,框架全局对象等]
  16. */
  17. private $obj;
  18. function __construct()//object $obj
  19. {
  20. parent::__construct();
  21. //$this->obj = $obj;
  22. //$this->resourse; 父类中已经实现,此类中可以直接使用
  23. //$tihs->resourseId; 父类中已经实现,此类中可以直接使用
  24. }
  25. /**
  26. * 获取资源操作
  27. * @return [type] [description]
  28. */
  29. protected function _get(){
  30. echo "get";
  31. //逻辑代码根据自己实际项目需要实现
  32. }
  33. /**
  34. * 新增资源操作
  35. * @return [type] [description]
  36. */
  37. protected function _post(){
  38. echo "post";
  39. //逻辑代码根据自己实际项目需要实现
  40. }
  41. /**
  42. * 删除资源操作
  43. * @return [type] [description]
  44. */
  45. protected function _delete(){
  46. //逻辑代码根据自己实际项目需要实现
  47. }
  48. /**
  49. * 更新资源操作
  50. * @return [type] [description]
  51. */
  52. protected function _put(){
  53. echo "put";
  54. //逻辑代码根据自己实际项目需要实现
  55. }
  56. }
  57. $server = new testServer();

以上所述就是本文的全部内容了,希望大家能够喜欢。

www.bkjia.comtruehttp://www.bkjia.com/PHPjc/997902.htmlTechArticlephp基于curl扩展制作跨平台的restfule 接口,phpcurlrestfule restfule 接口 适用的平台:跨平台 所依赖:curl扩展 git:https://git.oschina.net/anziguoer/re...

人气教程排行