ppajer / cache
PHP的一个基于文件系统的简单缓存。适用于缓存大型API响应,且很少需要更新的场景。
dev-master
2020-05-31 05:00 UTC
This package is auto-updated.
Last update: 2024-09-29 05:55:41 UTC
README
PHP的一个基于文件系统的简单缓存。适用于缓存大型API响应,且很少需要更新的场景。
安装
作为Composer包安装,或者下载此仓库并将类包含到项目中。
使用
要使数据自动缓存,请通过指定文件路径和以秒为单位的过期时间创建一个新的Cache实例。如果文件不存在,它将被创建。
$path = 'cache.json';
$expiry = 36000;
$cache = new Cache($path, $expiry);
if ($cache->needsUpdate()) {
$data = // get some new data;
$cache->write($data);
} else {
$data = $cache->read();
}
声明性更新
上述方法允许您控制何时以及是否更新缓存,但如果您不需要这种程度的控制,您可以简单地传递一个函数,该函数返回缓存过期时更新的数据,并让它处理其余部分。如果您数据不太可能动态变化,只需从缓存中读取最新数据,这非常有用。
function get_data() {
// do something here
return $data;
}
class API {
public static function get_data() {
// some api stuff
return $data;
}
}
$cache = new Cache('cache.json', 36000, 'get_data'); // Cache will update itself using the provided function if expired
$apiCache = new Cache('api.json', 36000, array(API::class, 'get_data')); // Accepts any callable that returns data
接口
interface ICache {
public function write($data) : bool;
public function read() : string;
public function needsUpdate() : bool;
}