mattmezza / cacheasy
我讨厌慢API,我在磁盘上缓存东西。
1.1
2018-04-03 15:32 UTC
Requires
- php: ^7.1
Requires (Dev)
- phpunit/phpunit: ^7.0
- squizlabs/php_codesniffer: ^3.2
This package is auto-updated.
Last update: 2024-09-17 09:43:36 UTC
README
我讨厌慢API,我在磁盘上缓存东西。
安装
composer require mattmezza/cacheasy
用法
使用字符串响应
$providerStrAPI = new class implements Cacheasy\StringProvider { public function get() : string { return (new SlowAPIsClient())->slowAPI(); } }; // ./cache is the cache path, 86400 is the time to live $cache = new Cache("./cache", 86400); // if slowAPI is not cached let's get the data and cache them $result = $cache->getString("slowAPI", $providerStrAPI); # this is slow :( $result2 = $cache->getString("slowAPI", $providerStrAPI); # this is blazing fast :) echo $result2;
使用JSON响应
$providerJsonAPI = new class implements Cacheasy\JsonProvider { public function get() : array { return (new SlowAPIsClient())->slowAPI(); } }; // ./cache is the cache path, 86400 is the time to live $cache = new Cache("./cache", 86400); // if slowAPI is not cached let's get the data and cache them $result = $cache->getJson("slowjsonAPI", $providerJsonAPI); # this is slow :( $result2 = $cache->getJson("slowjsonAPI", $providerJsonAPI); # this is blazing fast :) echo $result2["property"];
API
cacheString($key, $string) : string
:使用键缓存字符串cacheJson($key, $array) : array
:使用键将数组缓存为JSONhitString($key) : string
:尝试从缓存中恢复具有键的字符串hitJson($key) : array
:尝试从缓存中恢复具有键的JSONisCached($key) : bool
:检查键是否在磁盘上缓存且未过期getJson($key, $provider = null, bool $forceFresh = false) : array
:如果键已缓存,则返回hitJson(...)
,否则调用提供者。如果$provider为null且键未缓存,则抛出异常。如果$forceFresh设置为true
,则跳过isCached检查并调用提供者(最终缓存数据)。getString($key, $provider = null, bool $forceFresh = false) : string
:如果键已缓存,则返回hitString(...)
,否则调用提供者。如果$provider为null且键未缓存,则抛出异常。如果$forceFresh设置为true
,则跳过isCached检查并调用提供者(最终缓存数据)。invalidate($key) : void
:删除缓存的资源invalidateAll() : void
:删除所有缓存的资源
异常
MissingProviderException
:当调用get..(...)
对非缓存资源进行调用且未传递提供者,或当即使资源已缓存,方法也以null提供者和true
强制新鲜值调用时。NotCachedException
:当你想访问缓存但资源尚未缓存时。
开发
git clone https://github.com/mattmezza/cacheasy.git
cd cacheasy
composer test