缓存是精彩用于动态网站的数据临时储存,对于请求量大的或者数据量大的页面进行缓存可以有效增加体验感,也可以减轻数据库的请求压力。
缓存的方式很多,本例子是简单的用文件存放数据,定期清理数据。
逻辑:判断无缓存文件,有则直接返回,没有则查询数据库后写入缓存,下次直接用缓存文件,为了数据同步,定期清理缓存,设置一个清理的周期即可。
注意:目录要可写权限,实时更新数据可以不缓存,编辑或者删除数据源后及时移除文件。
如下生成的JSON文件,直接读取解析即可返回:

代码:
<?php
/**
* Created by BriskLan
* User: 1076963452@qq.com
* Date: 2019/5/20 22:55
*/
namespace blog\comm;
class cache
{
public $cachePath = BLOG_VIEW.'cache/';//缓存目录
public $cacheExpire = 86400;//缓存时间,秒,默认一天
public function __construct()
{
$this->auto_clean();
}
//设置缓存
function set_cache($id,$data)
{
if (!USE_CACHE){
return false;
}
$filePath = $this->cachePath.$id.'.json';
is_dir($this->cachePath) || mkdir($this->cachePath);
if (is_dir($this->cachePath) && is_writable($this->cachePath)){
if (!file_exists($filePath)){
file_put_contents($filePath,JsonReturn($data));
}
}
return 0;
}
//获取缓存
function get_cache($id)
{
if (!USE_CACHE){
return false;
}
$filePath = $this->cachePath.$id.'.json';
if (is_dir($this->cachePath) && is_writable($this->cachePath)){
if (file_exists($filePath)){
return json_decode(file_get_contents($filePath),true);
}
}
return false;
}
//重构缓存
function remove_cache($id)
{
if (!USE_CACHE){
return false;
}
$filePath = $this->cachePath.$id.'.json';
if (is_dir($this->cachePath) && is_writable($this->cachePath)){
if (file_exists($filePath)){
unlink($filePath);//先删除缓存
}
return true;
}
return false;
}
//定时清理
function auto_clean()
{
$path1 = dir($this->cachePath);
while (($item = $path1->read()) != false) {
if ($item == '.' || $item == '..') {
continue;
} else {
$file = $this->cachePath . '/' . $item;
$res = time() - filemtime($file);
if ($res > $this->cacheExpire) {
unlink($file);
}
}
}
}
}