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


Posted in PHP onMay 11, 2015

restfule 接口
适用的平台:跨平台
所依赖:curl扩展
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
{
  /**
   * 客户端请求的方式
   * @var string
   */
  private $method = '';
 
  /**
   * 客户端发送的数据
   * @var [type]
   */
  protected $param;
 
  /**
   * 要操作的资源
   * @var [type]
   */
  protected $resourse;
 
  /**
   * 要操作的资源id
   * @var [type]
   */
  protected $resourseId;
 
 
  /**
   * 构造函数, 获取client 请求的方式,以及传输的数据
   * @param object 可以自定义传入的对象
   */
  public function __construct()
  {
    //首先对客户端的请求进行验证
    $this->authorization();
 
    $this->method = strtolower($_SERVER['REQUEST_METHOD']);
 
    //所有的请求都是pathinfo模式
    $pathinfo = $_SERVER['PATH_INFO'];
 
    //将pathinfo数据信息映射为实际请求方法
    $this->getResourse($pathinfo);
 
    //获取传输的具体参数
    $this->getData();
 
    //执行响应
    $this->doResponse();
  }
 
  /**
   * 根据不同的请求方式,获取数据
   * @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;
    }
  }
 
  // 将pathinfo数据信息映射为实际请求方法
  private function getResourse($pathinfo){
 
    /**
     * 将pathinfo数据信息映射为实际请求方法
     * GET /users: 逐页列出所有用户;
     * POST /users: 创建一个新用户;
     * GET /users/123: 返回用户为123的详细信息;
     * PUT /users/123: 更新用户123;
     * DELETE /users/123: 删除用户123;
     *
     * 根据以上规则,将pathinfo第一个参数映射为需要操作的数据表,
     * 第二个参数映射为操作的id
     */
     
    $info = explode('/', ltrim($pathinfo, '/'));
    list($this->resourse, $this->resourseId) = $info;
  }
 
  /**
   * 验证请求
   */
  private function authorization(){
    $token = $_SERVER['HTTP_CLIENT_TOKEN'];
    $authorization = md5(substr(md5($token), 8, 24).$token);
    if($authorization != $_SERVER['HTTP_CLIENT_CODE']){
      //验证失败,输出错误信息给客户端
      $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

<?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.html [restful设计指南]
 */
/*** * * * * * * * * * * * * * * * * * * * * * * * * * ***\
 * 定义路由的请求方式                  *
 *                            *
 * $url_model=0                     *
 * 采用传统的URL参数模式                 *
 * http://serverName/appName/?m=module&a=action&id=1   *
 * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
 * PATHINFO模式(默认模式)               *
 * 设置url_model 为1                   *
 * http://serverName/appName/module/action/id/1/     *
 ** * * * * * * * * * * * * * * * * * * * * * * * * * * **
*/
class restClient
{
  //请求的token
  const token='yangyulong';
 
  //请求url
  private $url;
   
  //请求的类型
  private $requestType;
   
  //请求的数据
  private $data;
   
  //curl实例
  private $curl;
 
  public $status;
 
  private $headers = array();
  /**
   * [__construct 构造方法, 初始化数据]
   * @param [type] $url     请求的服务器地址
   * @param [type] $requestType 发送请求的方法
   * @param [type] $data    发送的数据
   * @param integer $url_model  路由请求方式
   */
  public function __construct($url, $data = array(), $requestType = 'get') {
     
    //url是必须要传的,并且是符合PATHINFO模式的路径
    if (!$url) {
      return false;
    }
    $this->requestType = strtolower($requestType);
    $paramUrl = '';
    // PATHINFO模式
    if (!empty($data)) {
      foreach ($data as $key => $value) {
        $paramUrl.= $key . '=' . $value.'&';
      }
      $url = $url .'?'. $paramUrl;
    }
     
    //初始化类中的数据
    $this->url = $url;
     
    $this->data = $data;
    try{
      if(!$this->curl = curl_init()){
        throw new Exception('curl初始化错误:');
      };
    }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 设置get请求的参数]
   * @return [type] [description]
   */
  public function _get() {
 
  }
   
  /**
   * [_post 设置post请求的参数]
   * post 新增资源
   * @return [type] [description]
   */
  public function _post() {
 
    curl_setopt($this->curl, CURLOPT_POST, 1);
 
    curl_setopt($this->curl, CURLOPT_POSTFIELDS, $this->data);
     
  }
   
  /**
   * [_put 设置put请求]
   * put 更新资源
   * @return [type] [description]
   */
  public function _put() {
     
    curl_setopt($this->curl, CURLOPT_CUSTOMREQUEST, 'PUT');
  }
   
  /**
   * [_delete 删除资源]
   * delete 删除资源
   * @return [type] [description]
   */
  public function _delete() {
    curl_setopt($this->curl, CURLOPT_CUSTOMREQUEST, 'DELETE');
 
  }
   
  /**
   * [doRequest 执行发送请求]
   * @return [type] [description]
   */
  public function doRequest() {
    //发送给服务端验证信息
    if((null !== self::token) && self::token){
      $this->headers = array(
        'Client_Token: '.self::token,
        'Client_Code: '.$this->setAuthorization()
      );
    }
 
    //发送头部信息
    $this->setHeader();
 
    //发送请求方式
    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;
    }
    //执行curl请求
    $info = curl_exec($this->curl);
 
    //获取curl执行状态信息
    $this->status = $this->getInfo();
    return $info;
  }
 
  /**
   * 设置发送的头部信息
   */
  private function setHeader(){
    curl_setopt($this->curl, CURLOPT_HTTPHEADER, $this->headers);
  }
 
  /**
   * 生成授权码
   * @return string 授权码
   */
  private function setAuthorization(){
    $authorization = md5(substr(md5(self::token), 8, 24).self::token);
    return $authorization;
  }
  /**
   * 获取curl中的状态信息
   */
  public function getInfo(){
    return curl_getinfo($this->curl);
  }
 
  /**
   * 关闭curl连接
   */
  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();
 
//获取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 17:26:37
 */
 
include './ApiServer.php';
 
class testServer extends apiServer
{
  /**
   * 先执行apiServer中的方法,初始化数据
   * @param object $obj 可以传入的全局对象[数据库对象,框架全局对象等]
   */
   
  private $obj;
 
  function __construct()//object $obj
  {
    parent::__construct();
    //$this->obj = $obj;
    //$this->resourse; 父类中已经实现,此类中可以直接使用
    //$tihs->resourseId; 父类中已经实现,此类中可以直接使用
  }
   
  /**
   * 获取资源操作
   * @return [type] [description]
   */
  protected function _get(){
    echo "get";
    //逻辑代码根据自己实际项目需要实现
  }  
 
  /**
   * 新增资源操作
   * @return [type] [description]
   */
  protected function _post(){
    echo "post";
    //逻辑代码根据自己实际项目需要实现
  }
 
  /**
   * 删除资源操作
   * @return [type] [description]
   */
  protected function _delete(){
    //逻辑代码根据自己实际项目需要实现
  }
 
  /**
   * 更新资源操作
   * @return [type] [description]
   */
  protected function _put(){
    echo "put";
    //逻辑代码根据自己实际项目需要实现
  }
}
 
$server = new testServer();

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

PHP 相关文章推荐
PHP脚本数据库功能详解(下)
Oct 09 PHP
第十二节--类的自动加载
Nov 16 PHP
PHP Memcached + APC + 文件缓存封装实现代码
Mar 11 PHP
php对csv文件的读取,写入,输出下载操作详解
Aug 10 PHP
IIS6.0 开启Gzip方法及PHP Gzip函数分享
Jun 08 PHP
PHP中substr()与explode()函数用法分析
Nov 24 PHP
PHP实现抓取HTTPS内容
Dec 01 PHP
PHP实现清除MySQL死连接的方法
Jul 23 PHP
php文件上传、下载和删除示例
Aug 28 PHP
PHP实现的一致性Hash算法详解【分布式算法】
Mar 31 PHP
PHP实现将多个文件压缩成zip格式并下载到本地的方法示例
May 23 PHP
PHP两个n位的二进制整数相加问题的解决
Aug 26 PHP
PHP SPL标准库中的常用函数介绍
May 11 #PHP
PHP中的类型约束介绍
May 11 #PHP
PHP SPL标准库之接口(Interface)详解
May 11 #PHP
PHP SPL标准库之文件操作(SplFileInfo和SplFileObject)实例
May 11 #PHP
PHP设计模式之适配器模式代码实例
May 11 #PHP
Mac环境下php操作mysql数据库的方法分享
May 11 #PHP
PHP设计模式之装饰者模式代码实例
May 11 #PHP
You might like
如何判断php数组的维度
2013/06/10 PHP
smarty模板引擎之分配数据类型
2015/03/30 PHP
php 三大特点:封装,继承,多态
2017/02/19 PHP
2017年最新PHP经典面试题目汇总(上篇)
2017/03/17 PHP
jquery列表拖动排列(由项目提取相当好用)
2014/06/17 Javascript
javascript表单验证和Window详解
2014/12/11 Javascript
javascript 构造函数方式定义对象
2015/01/02 Javascript
jquery中EasyUI实现异步树
2015/03/01 Javascript
jQuery实现点击水纹波动动画
2016/04/10 Javascript
Zabbix添加Node.js监控的方法
2016/10/20 Javascript
JS弹出窗口的运用与技巧大全
2016/11/01 Javascript
Jquery Easyui菜单组件Menu使用详解(15)
2016/12/18 Javascript
bootstrapValidator 重新启用提交按钮的方法
2017/02/20 Javascript
AngularJS实现的JSONP跨域访问数据传输功能详解
2017/07/20 Javascript
Parcel.js + Vue 2.x 极速零配置打包体验教程
2017/12/24 Javascript
微信小程序websocket实现聊天功能
2020/03/30 Javascript
jQuery实现鼠标移入移出事件切换功能示例
2018/09/06 jQuery
如何在vue 中使用柱状图 并自修改配置
2021/01/21 Vue.js
详解Python中expandtabs()方法的使用
2015/05/18 Python
Python读取一个目录下所有目录和文件的方法
2016/07/15 Python
python学习之面向对象【入门初级篇】
2017/01/21 Python
Python批量查询域名是否被注册过
2017/06/21 Python
python 寻找优化使成本函数最小的最优解的方法
2017/12/28 Python
解决Python安装后pip不能用的问题
2018/06/12 Python
python3 json数据格式的转换(dumps/loads的使用、dict to str/str to dict、json字符串/字典的相互转换)
2019/04/01 Python
Python函数参数匹配模型通用规则keyword-only参数详解
2019/06/10 Python
python async with和async for的使用
2019/06/20 Python
基于python实现可视化生成二维码工具
2020/07/08 Python
美国最大的网上冲印店:Shutterfly
2017/01/01 全球购物
PatPat香港:婴童服饰和亲子全家装在线购物
2020/09/27 全球购物
SQL Server 2000数据库的文件有哪些,分别进行描述
2013/03/30 面试题
我的中国梦演讲稿初中篇
2014/08/19 职场文书
学校班子个人对照检查材料思想汇报
2014/09/27 职场文书
党员心得体会范文2016
2016/01/23 职场文书
2019下半年英语教师的教学工作计划(3篇)
2019/09/25 职场文书
Python连接Postgres/Mysql/Mongo数据库基本操作大全
2021/06/29 Python