<?php
// echo dirname(__FILE__).'/cache';
// exit;
/**
- 静态缓存
*/
class Cacha {
private $_dir; // 目录
const EXT = '.txt'; // 后缀
public function __construct()
{
$this->_dir = dirname(__FILE__).'/cache/';
}
public function catchData($key, $value = '', $catchTime = 0)
{
$filename = $this->_dir.$key.self::EXT; // 拼装文件名
if (!empty($value)) { // 写入缓存
// 删除缓存
if (is_null($value)) {
return @unlink($filename);
}
// 获取文件目录
$dir = dirname($filename);
if (!is_dir($dir)) {
mkdir($dir,0777);
}
$catchTime = sprintf('%011d', $catchTime);
file_put_contents($filename, $catchTime.json_encode($value));
return true;
}
if (!is_file($filename)) {
return false;
}
// 获取缓存失效时间
$contents = file_get_contents($filename);
$catchTime = (int)substr($contents, 0, 11);
$value = substr($contents, 11);
// echo $value;exit;
// 缓存失效
if ($catchTime != 0 && ($catchTime + filemtime($filename) < time())) {
unlink($filename);
return false;
}
return json_decode($value,true);
}
}
$data = [
'id' => 1,
'name' => 'lw',
'info' => [
'sex' => '男',
'age' => 18,
],
];
$test = new Cacha;
var_dump(($test->catchData('test')));