-
-
Notifications
You must be signed in to change notification settings - Fork 0
Quick start guide
composer require phpgt/filecacheuse GT\FileCache\Cache;
$cache = new Cache(
__DIR__ . "/cache",
60 * 5
);The first argument is the directory where cache files will be stored. The second argument is the lifetime, in seconds. In this example, entries remain fresh for 5 minutes.
If we omit the second argument, the default lifetime is 1 hour.
There is also a third optional constructor argument for supplying a FileAccess instance directly. Most applications do not need that, but it is available for advanced integration and testing.
$weather = $cache->get("weather:london", function():array {
return [
"summary" => "Cloudy",
"temperature" => 14,
];
});On the first call, the callback runs and its return value is written to a cache file. On later calls with the same key, the cached value is returned immediately until the entry expires.
The cache key is the logical name of the entry:
$user = $cache->get("user:105:profile", fn() => loadUserProfile(105));Keys do not need to be limited to filenames. The library safely escapes characters that would otherwise affect paths, so values like URLs can be used directly:
$page = $cache->get("https://example.com/products/105", fn() => fetchPage());The stored filename still remains readable for debugging because it uses URL-style escaping rather than an opaque hash.
If we know the value should be a string, integer, float, boolean, date, array, or class instance, there are typed getters available:
$username = $cache->getString("user:105:name", fn() => "Cody");
$count = $cache->getInt("dashboard:visits", fn() => 0);The full set of getters is covered in Type safety.
PHP.GT/FileCache is a separately maintained component of PHP.GT/WebEngine.