• RESTful API 设计


    网络应用程序,分为前端和后端两个部分。当前的发展趋势,就是前端设备层出不穷(手机、平板、桌面电脑、其他专用设备......)。

    因此,必须有一种统一的机制,方便不同的前端设备与后端进行通信。这导致API构架的流行。

    RESTful API 设计要素详见此文 : RESTful API 设计指南

    以下简诉API的测试和它在PHP中的异常处理:

    安装浏览器扩展工具 Restlet Client - DHC ,用于API的调试/测试

     

    异常处理:

        /**
         * 常用状态码
         * @var [type]
         */
        private $_statusCodes = array(
            200 => 'OK',
            204 => 'No Content',
            400 => 'Bad Request',
            401 => 'Unauthorized',
            403 => 'Forbidden',
            404 => 'Not Found',
            405 => 'Method Not Allowed',
            500 => 'Server INternal Error'
        );
        /**
         * 判断请求方法和资源对象
         * @return [type] [description]
         */
        public function run()
        {
            //异常捕获,以免被暴露在前台
            try {
                $this->_setupRequestMethod();
                $this->_setupResource();
                if ($this->_resourceName == 'users') {
                    return $this->_json($this->_handleuser());
                } else {
                    return $this->_json($this->_handleArticle());
                }
            } catch (Exception $e) {
                $arr['error'] = $e->getMessage(); 
                $this->_json($arr, $e->getCode());
            }
        }
        /**
         * 输出JSON
         * @param  [type] $array [description]
         * @return [type]        [description]
         */
        private function _json($array, $code = 0)
        {
            //同步响应码
            if ($code > 0 && $code !== 200 && $code !== 204) {
                header("HTTP/1.1 " . $code . " " . $this->_statusCodes[$code]);
            }
            
            header('Content-Type:application/json;charset=utf-8');
            // echo json_encode($array, JSON_UNESCAPED_UNICODE);
            echo json_encode($array);
            exit();
        }
        /**
         * 获取请求参数
         * @return [type] [description]
         */
        private function _getBodyParams()
        {
            //所传参数用双引号
            $raw = file_get_contents('php://input');
            if (empty($raw)) {
                throw new Exception('请求参数错误', 400);
            }
            return json_decode($raw, true);
        }
  • 相关阅读:
    fenby C语言 P9
    fenby C语言 p7
    fenby C语言 P6
    fenby C语言
    让博客园博客自动生成章节目录索引
    python学习之路:生成器并行运算
    Python学习之路:生成器
    Python学习之路:装饰器实现终极版
    Python学习之路:装饰器实现2
    Python学习之路:装饰器实现
  • 原文地址:https://www.cnblogs.com/lishalom/p/6617168.html
Copyright © 2020-2023  润新知