phpgt / filecache
将数据缓存在本地文件中。
v1.0.0
2023-07-14 18:06 UTC
Requires
- php: >=8.1
- phpgt/typesafegetter: ^v1.2.4
Requires (Dev)
- phpmd/phpmd: ^2.13
- phpstan/phpstan: ^1.10
- phpunit/phpunit: ^10.1
- squizlabs/php_codesniffer: ^3.7
This package is auto-updated.
Last update: 2024-09-14 20:35:44 UTC
README
通过在本地文件中缓存像HTTP调用或数据库查询等昂贵的操作结果,可以最小化这些操作。这可以提高性能,减少网络使用,并避免速率限制,仅举一些常见的好处。此库提供了一个单函数来定义在哪里缓存、缓存什么以及何时缓存。默认情况下,如果没有指定有效时间,有效期为1小时。
示例用法:获取用户IP地址的经纬度
对每个页面视图进行HTTP调用是一个昂贵的操作,但在这个示例中,我们想使用远程服务来提供我们当前IP地址的估计经纬度。
第一次看到IP地址时需要执行HTTP调用,但后续调用将能够利用缓存。
$ipAddress = $_SERVER["REMOTE_ADDR"]; $fileCache = new Gt\FileCache\Cache("/tmp/ip-address-geolocation"); // This function uses file_get_contents to contact the remote server // at ipinfo.io, a costly operation. We will pass the lookup function // into the cache, so it is only called when we don't have a fresh result. $lookup = function()use($ipAddress):string { $jsonString = file_get_contents("https://ipinfo.io/$ipAddress"); $obj = json_decode($jsonString); return $obj->loc; } $location = $fileCache->get("lat-lon", $lookup); echo "Your location is: $location";