PHP开发APP接口(五):首页APP接口开发

方案一:读取数据库方式开发首页接口

流程: 从数据库获取信息 -> 封装 -> 生成接口数据
应用场景:数据时效性,比较高的系统
学习要点:
1. 掌握如何获取数据;
2. 掌握如何将获取的数据生成通信数据;
详细流程:
http请求 -> 服务器 -> 查询数据 -> 返回数据

文件链接:var/www/app/list.php

// 封装输出数据类
require_once('./response.php');

// 引入的 db.php 数据库类需要进行改动
require_once('./db.php');


$page = isset($_GET['page']) ? $_GET['page'] : 1;
$pageSize = isset($_GET['pagesize']) ? $_GET['pagesize'] : 1;

if (!is_numeric($page) || !is_numeric($pageSize)) {
    return Response::show(401, '数据不合法');
}

$offset = ($page-1) * $pageSize;
$sql = "select * from mk_user where score != 0 order by id desc limit " . $offset . "," . $pageSize;

// $sql = "select * from mk_user";
// $result = mysql_query($sql, $connect);
// echo mysql_fetch_row($result);
// var_dump($result);

try {
    $connect = Db::getInstance()->connect();
} catch(Exception $e) {
    return Response::show(403, '数据库连接失败', $users);
}

$result = mysql_query($sql, $connect);

$users = array();
while ($user = mysql_fetch_assoc($result)) {
    $users[] = $user;
}


if($users) {
    return Response::show(200, '首页数据获取成功', $users);
} else {
    return Response::show(400, '首页数据获取失败', $users);
}

文件链接:var/www/app/db.php
~~~
class Db {
static private instance;//staticprivate_connectSource; // 连接的资源
private $_dbConfig = array(
‘host’ => ‘192.168.2.110’,
‘user’ => ‘root’,
‘password’ => ‘root’,
‘database’ => ‘muke’,
);

// 构造函数需要设置成私有,防止被其他类实例化
private function __construct() {
}

// 访问实例的公共方法
static public function getInstance() {
    // 是否实例,如果没有则实例化类
    if (!self::$_instance instanceof self) {
        self::$_instance = new self();
    }

    return self::$_instance;
}

public function connect() {
    if(!self::$_connectSource) {
        self::$_connectSource = mysql_connect($this->_dbConfig['host'], $this->_dbConfig['user'], $this->_dbConfig['password']);

        if(!self::$_connectSource) {
            // 此处注意,如果数据库连接失败,需要抛出一个异常,以供连接时使用,连接需要用 try-catch 测试连接。
            throw new Exception('mysql connect error ' . mysql_error());
            // die('mysql connect error'. mysql_error());
        }

        mysql_select_db($this->_dbConfig['database'], self::$_connectSource);
        mysql_query("set names UTF8", self::$_connectSource);

        return self::$_connectSource;
    }
}

}



----------
##方案二:读取缓存方式开发首页接口
流程:从数据库获取信息 -> 封装(读取缓存,再次读取) -> 返回数据
用途:减少数据库压力
学习要点:
1. 掌握静态缓存如何设置缓存失效时间;
2. 如何设置缓存;
详细流程:
![](https://box.kancloud.cn/c289d209a55ec14e495212d69f0d68c9_602x330.png)

*文件连接:var/www/app/list.php*


*重新定义一下缓存文件类,把缓存路径改为缓存失效时间:var/www/app/file.php*

class File {
private _dir;  // 默认路径  
    const EXT = ‘.txt’;  
    public function __construct() {  
        // dirname() 当前文件目录
this->_dir = dirname(FILE) . ‘/files/’; //默认路径为当前文件下的files下
}

/**
 * [cacheData description]
 * @Author   ZJC
 * @DateTime 2017-02-15T10:31:38+0800
 * @param    [type]                   $key       [缓存文件文件名]
 * @param    string                   $value     [缓存数据]
 * @param    integer                  $cacheTime [缓存失效时间]
 * @return   [type]                          [description]
 */
public function cacheData($key, $value = '', $cacheTime = 0) {
    $filename = $this->_dir .$key . self::EXT;
    if ($value !== '') {    // 将value值写入缓存
        if(is_null($value)) {
            return @unlink($filename);
        }
        // 判断是否存在文件目录,如果不存在,则创建
        $dir = dirname($filename);
        if (!is_dir($dir)) {
            mkdir($dir, 0777);
        }

        $cacheTime = sprintf('%011d', $cacheTime);

        // file_put_contents:将一个字符串写入文件
        // int file_put_contents ( string $filename , mixed $data [, int $flags = 0 [, resource $context ]] )
        // $data部分最好为字符串形式,因为不支持多维数组;(序列化,JSON都可以)
        return file_put_contents($filename, $cacheTime . json_encode($value));   // c成功返回字节数,失败返回FALSE

    }

    if(!is_file($filename)) {   // 显示缓存
        return FALSE;
    }
    $contents = file_get_contents($filename);
    $cacheTime = (int)substr($contents, 0, 11);
    $value = substr($contents, 11);

    if($cacheTime != 0 && $cacheTime + filemtime($filename) < time()) {
        unlink($filename);
        return FALSE;
    }
    return json_decode($value, true);

}

}



----------
##方案三:定时读取缓存方式开发首页接口
流程:http请求 -> 缓存(crontab从数据库获取缓存) -> 封装并返回数据
学习要点:
1. 掌握如何编写定时脚本程序
2. 理解服务器如何提前准备数据
![](image/QQ截图20170222095810.png)

*增加crontab执行文件:var/www/app/cron.php*

// 让crontab定时执行的脚本程序 /5 * * * /usr/bin/php /var/www/app/cron.php

// 获取user表中6条数据

require_once(‘./db.php’);
require_once(‘./file.php’);

$sql = “select * from mk_user where score != 0 order by id desc”;

try {
connect = Db::getInstance()->connect();  
} catch(Exception
e) {
// e>getMessage();//fileputcontents(./logs/.date(ymd)..txt,e->getMessage());
return;
}

result=mysqlquery(sql, $connect);

users=array();while(user = mysql_fetch_assoc(result)) {users[] = $user;
}

$file = new File();

if(users) {  
    // 有数据的话,把数据写到缓存文件里
file->cacheData('index_cron_cache', $users);
} else {
file_put_contents(‘./logs/’ . date(‘y-m-d’) . ‘.txt’, “没有相关数据”);
}
return;


*上面的crontab没5分钟执行一次,当有数据时,在list.php文件开头能够查询到数据:var/www/app/list.php*

require_once(‘./response.php’);
require_once(‘./file.php’);

// 增加下面对缓存进行查询
file=newFile();data = file>cacheData(indexcroncache);if(data) {
return Response::show(200, ‘首页数据获取成功’, data);  
} else {  
    return Response::show(400, ‘首页数据获取失败’,
data);
}

require_once(‘./db.php’);
“`

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值