andydune/retain-cache-on-data-absent

代码允许在无法检索到新数据时恢复缓存中的数据。

v1.1.1 2018-06-19 13:41 UTC

This package is auto-updated.

Last update: 2024-09-14 21:41:14 UTC


README

Build Status Software License Packagist Version Total Downloads

如果无法检索到新数据,则允许从缓存中恢复数据。

安装

使用 composer 安装

composer require andydune/retain-cache-on-data-absent

或者如果 composer 未在全局范围内安装

php composer.phar require andydune/retain-cache-on-data-absent

或者编辑你的 composer.json

"require" : {
     "andydune/retain-cache-on-data-absent": "^1"
}

然后执行以下命令

php composer.phar update

问题

你的脚本从外部 API 获取数据。例如,从 crr 获取货币汇率。

没有必要每次需要时都提取数据。因此,我们使用缓存。但如果缓存变旧,但 API 没有数据出现呢?可能是网络错误或银行网站故障。

这个小程序库有助于避免从检索器中缺失数据。缓存数据不会过期,如果没有新的数据出现,则使用缓存中的旧数据。

使用

use Symfony\Component\Cache\Simple\FilesystemCache;
use AndyDune\RetainCacheOnDataAbsent\Cache;

$cacheAdapter = new FilesystemCache('test', 3600, '<root cache dir>');
$cache = new Cache($cacheAdapter, function () {
    /*
        $data = false; // no data - return data from old cache
        $data = 'very useful data to cache and use'; // update cache and return this data
    */
    return $data;
});
$result = $cache->get('data'); // use any key - it is used only for cache key