-
-
Notifications
You must be signed in to change notification settings - Fork 0
Home
Making slow operations like HTTP calls or database queries can be minimised by caching the result of the operations in local files. This can improve performance, reduce network usage, and avoid rate limiting, to name some common benefits. This library provides a single function to define where to cache, what to cache, and when to cache. A validity of 1 hour is set by default.
We provide a cache directory, a cache key, and a callback that knows how to produce the value. If a fresh cached value already exists, the callback is skipped. If the entry is missing or expired, the callback runs and its return value is written to disk.
It's an expensive operation to make an HTTP call for every page view, but in this example we want to use a remote service to provide us with the estimated latitude/longitude of the current IP address.
The first time we see the IP address will have to make an HTTP call, but subsequent calls will be able to take advantage of the cache.
use GT\FileCache\Cache;
$ipAddress = $_SERVER["REMOTE_ADDR"];
$cache = new Cache("/tmp/ip-address-geolocation", 60 * 10);
$location = $cache->get("ipinfo:$ipAddress", function()use($ipAddress):string {
$json = file_get_contents("https://ipinfo.io/$ipAddress");
$data = json_decode($json);
return $data->loc;
});
echo $location;In this example, each IP address gets its own cache entry, the cache lives for 10 minutes, and repeated requests for the same address reuse the file until it expires.
Start with the Quick start guide to set up a cache directory and your first cache lookup.
PHP.GT/FileCache is a separately maintained component of PHP.GT/WebEngine.