restfule 接口

夜敏吖_5146

夜敏吖_5146

2016-05-26

1137人浏览

原创

restfule 接口
适用的平台:跨平台
所依赖:curl扩展

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 class="brush:php;toolbar:false;">';
            print_r($e->getMessage());
            echo '
';         }           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 class="brush:php;toolbar:false;">';
print_r($info);
echo '
';

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速学视频免费教程(入门到精通)

PHP怎么学习?PHP怎么入门?PHP在哪学?PHP怎么学才快?不用担心,这里为大家提供了PHP速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!

下载

相关标签:

本站声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn

相关专题

更多
Navicat创建数据库教程
Navicat创建数据库教程

本专题整理Navicat创建数据库相关教程,介绍新建前的准备、基础设置和创建后的检查方法。内容兼顾入门学习及实际使用需求,帮助用户了解不同数据库类型下的操作差异,为后续建表、保存数据和日常管理提供参考。

2026.11.20

20

7

Navicat入门教程大全
Navicat入门教程大全

本专题整理Navicat入门教程,从认识软件界面到开展数据库操作,介绍初次使用需要了解的知识和方法。内容兼顾连接配置、数据管理及日常使用中的疑问,方便用户按学习进度查阅,为后续实践和独立操作打好基础。

2026.11.20

20

17

Navicat数据库连接配置指南
Navicat数据库连接配置指南

从确认数据库信息到建立可用连接,本专题串联Navicat连接数据库的相关知识和操作方法。既有初次配置时需要了解的基础内容,也有连接后的检查思路,方便用户按实际需求查阅教程,逐步熟悉数据库连接的设置流程。

2026.11.20

0

10

PHP8.6数组与数据处理教程
PHP8.6数组与数据处理教程

本专题汇总PHP8.6数组与数据处理教程,涵盖CSV读取和导出、引用遍历删除、array_filter回调模式、配置键名冲突、pathinfo文件名校验、GMP大整数进制转换及UTF-8正则筛选,说明升级兼容变化、输入范围和失败处理方法。

2026.11.20

60

8

PHP8.6升级迁移教程
PHP8.6升级迁移教程

本专题汇总PHP8.6升级迁移与弃用接口改造教程,涵盖反射调用、对象属性赋值、标识符更名、构造函数与__debugInfo调整,以及插件类名检查、常量导出、ArrayIterator排序、SPL和DTO查询参数转换,帮助梳理弃用提示并完成代码兼容改造。

2026.11.20

0

10

PHP8.6安装配置与FPM运维教程
PHP8.6安装配置与FPM运维教程

本专题汇总PHP8.6正式版安装部署与FPM运维教程,涵盖Linux并存安装、独立ini配置、扩展重新编译、Nginx切换与回滚、FPM状态监控和慢日志排查,以及环境变量、请求超时、OPcache刷新和预加载配置。

2026.11.20

40

10

Nginx CVE-2026-123007排查与防护指南
Nginx CVE-2026-123007排查与防护指南

Nginx HTTP/2漏洞该怎么修复?本专题围绕CVE-2026-123007,介绍安全版本升级、模块兼容检查和配置恢复方法,以及日志排查、权限设置等后续加固操作,方便你按实际部署情况查找对应教程。

2026.11.20

40

8

GoFrame框架Web开发与路由中间件
GoFrame框架Web开发与路由中间件

本专题聚焦GoFrame框架的Web开发,拆解路由注册与匹配规则、请求参数获取、参数校验与中间件执行顺序,说明统一响应、JWT鉴权、文件上传与接口文档生成的落地方式,并补充优雅重启与测试实践。

2026.11.17

80

15

GoFrame框架安装与gf命令行工具
GoFrame框架安装与gf命令行工具

本专题围绕GoFrame框架的安装与工具链配置展开,讲清Go版本要求、gf命令行的安装方式、代理镜像与依赖准备,说明项目初始化、热编译、交叉编译打包的做法,并整理安装阶段的常见报错与验证步骤。

2026.11.17

100

15

热门下载

更多
网站特效
/
网站源码
/
网站素材
/
前端模板

精品课程

更多
热门推荐
/
最新课程
phpStudy极速入门视频教程
phpStudy极速入门视频教程

共6课时 | 54.8万人学习

独孤九贱(4)_PHP视频教程
独孤九贱(4)_PHP视频教程

共89课时 | 134.5万人学习