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";