• PHP 开发 APP 接口--读取数据库方式


    方案一:读取数据库方式

    从数据库读取信息→封装→生成接口数据

    应用场景:

    数据时效性比较高的系统

    方案二:读取缓存方式

    从数据库获取信息(第一次设置缓存或缓存失效时)→封装(第一次设置缓存或缓存失效时)→返回数据

                                                                            ↓                                              ↑

                                                                         缓存(缓存生效时)     →   →    →    →

    方案三:定时读取缓存方式(crontab 定时任务)

                      封装并返回数据

                              ↑

    数据库→crontab→缓存 

                              ↑

                         http 请求

    =======

    方案一:

    (安装Start BlueStacks 安卓模拟器)

    流程:

    http 请求→服务器→查询数据(使用reviewdb库)→返回数据

    db.php:

     1 <?php
     2 /*
     3  * 单例模式连接数据库
     4  */
     5 class DB{
     6     static private $_instance;    //非public的类的实例的静态成员变量
     7     static private $_connectSource;    //连接数据库返回的资源句柄
     8     private $_dbConfig = array(
     9         'host'=>'127.0.0.1',
    10         'username'=>'root',
    11         'pwd'=>'',
    12         'database'=>'reviewdb'
    13     );
    14 
    15     private function __construct(){    //非public 的构造函数
    16     }
    17 
    18     static public function getInstance(){    //访问实例的公共静态方法
    19         if(!self::$_instance instanceof self){
    20             self::$_instance = new self();
    21         }
    22         return self::$_instance;
    23     }
    24 
    25     public function connect(){
    26         if(!self::$_connectSource){
    27             //连接mysql服务
    28             self::$_connectSource = @mysql_connect($this->_dbConfig['host'],$this->_dbConfig['username'],$this->_dbConfig['pwd']);
    29             if(!self::$_connectSource){
    30                 //抛出异常
    31                 throw new Exception('mysql connect error'.mysql_error());
    32             }
    33             //选择数据库
    34             mysql_select_db($this->_dbConfig['database'],self::$_connectSource);
    35             //设置字符集
    36             mysql_query('set names "UTF8"',self::$_connectSource);
    37         }
    38         return self::$_connectSource; //返回资源
    39     }
    40 }

    list.php

     1 <?php
     2 require_once 'response.php';
     3 require_once 'db.php';
     4 
     5 $page = isset($_GET['page'])?$_GET['page']:1;
     6 $pageSize = isset($_GET['pageSize'])?$_GET['pageSize']:1;
     7 if(!is_numeric($page) || !is_numeric($pageSize)){
     8     return @Response::show(401,'数据不合法');
     9 }
    10 
    11 $offset = ($page-1)*$pageSize; //每页起始数
    12 $sql = 'select * from review where is_enabled = 1 order by creation_time desc limit '.$offset.','.$pageSize;
    13 
    14 #捕获异常
    15 try{
    16     $connect = DB::getInstance()->connect();
    17 }catch(Exception $e){
    18     return Response::show(403,'数据库连接失败');
    19 }
    20 
    21 $res = mysql_query($sql,$connect);
    22 $vals = array();
    23 while($val = mysql_fetch_assoc($res)){
    24     $vals[] = $val; //二维数组
    25 }
    26 
    27 if($vals){
    28     return Response::show(200,'首页数据获取成功',$vals);
    29 }else{
    30     return Response::show(400,'首页数据获取失败',$vals);
    31 }

    response.php

      1 <?php
      2 
      3 class Response{
      4     const JSON = 'json';
      5     //封装的综合方法,默认的数据类型为json
      6     public static function show($code,$message = '',$data = '',$type = self::JSON){
      7         
      8         if(!is_numeric($code)){
      9             return '';
     10         }
     11         //供测试数组使用
     12         $result = array(
     13             'code' => $code,
     14             'message' => $message,
     15             'data' => $data
     16         );
     17         //通过get参数判断通信数据类型
     18         $typelist = array('json','xml','array'); // array为测试使用
     19         if(isset($_GET['type'])){
     20             if(in_array(strtolower($_GET['type']),$typelist)){
     21                 $type = strtolower($_GET['type']);
     22             }else{
     23                 $type = self::JSON;
     24             }
     25         }else{
     26             $type = self::JSON;
     27         }
     28 
     29         if($type == 'json'){
     30             self::json($code,$message,$data);
     31         }else if($type == 'xml'){
     32             self::xml($code,$message,$data);
     33         }else if($type == 'array'){
     34             var_dump($result);    //仅供测试
     35         }
     36     }
     37 
     38     /**
     39     * 按json方式输出通信数据
     40     * @param integer $code 状态码
     41     * @param string $message 提示信息
     42     * @param array $data 数据
     43     * return string
     44     */
     45     //设置静态方法
     46     public static function json($code,$message = '',$data = array()){
     47         if(!is_numeric($code)){
     48             return '';
     49         }
     50         //状态码、信息、数据组成的新数组
     51         $result = array(
     52             'code' => $code,
     53             'message' => $message,
     54             'data' => $data
     55         );
     56 
     57         echo json_encode($result);
     58         exit();
     59     }
     60 
     61     /**
     62     * 按 xml 方式输出通信数据
     63     * @param integer $code 状态码
     64     * @param string $message 提示信息
     65     * @param array $data 数据
     66     * return string
     67     */
     68     public static function xml($code,$message,$data){
     69 
     70         if(!is_numeric($code)){
     71             return '';
     72         }
     73 
     74         $result = array(
     75             'code' => $code,
     76             'message' => $message,
     77             'data' => $data
     78         );
     79 
     80         //修改 http 头信息
     81         header("Content-Type:text/xml");
     82         //xml头信息
     83         $xml = "<?xml version='1.0' encoding='utf-8'?>";
     84         //根节点开始标签
     85         $xml .= "<root>";
     86 
     87         $xml .= self::xmlToEncode($result);
     88 
     89         //根节点结束标签
     90         $xml .= "</root>";
     91 
     92         echo $xml;
     93         exit();
     94     }
     95 
     96     //解析$result至xml
     97     public static function xmlToEncode($data){
     98         $xml = $attr = "";
     99         foreach($data as $k=>$v){
    100             //如果$k是数字(data(code,message,data中的data)数据里面还含有索引数组),要进行如下判断
    101             if(is_numeric($k)){
    102                 $attr = "id='{$k}'";
    103                 $k = 'item ';
    104             }
    105 
    106             $xml .= "<{$k}{$attr}>";
    107             //如果$v是数组,则递归调用该方法
    108             if(is_array($v)){
    109                 $xml .= self::xmlToEncode($v);
    110             }else{
    111                 $xml .= $v;
    112             }
    113             $xml .= "</{$k}>";
    114         }
    115 
    116         return $xml;
    117     }
    118 }
  • 相关阅读:
    git config 命令各参数有何区别
    Git 初始化
    Linux 安装 Git
    在Mac OS 上安装 Git
    maven 部署到远程仓库(私服)
    Git与SVN的区别
    windows挂载NFS文件系统无法访问/修改文件解决
    mysql5.7写入数据时间相差13/14小时解决
    mysql配置文件不生效解决
    springdata jpa mysql5.7写入中文乱码解决
  • 原文地址:https://www.cnblogs.com/lxj0205/p/9995581.html
Copyright © 2020-2023  润新知