-
-
Notifications
You must be signed in to change notification settings - Fork 0
Callback handling
Every call to GT\FileCache\Cache is built around a callback.
The callback tells the cache how to produce a fresh value if the cached entry is missing or expired. If a fresh cached value already exists, the callback is not executed.
$profile = $cache->get("user:105:profile", fn() => loadUserProfile(105));The callback is executed when:
- there is no cache file for the key
- the cache file exists but is older than the configured lifetime
If the cache file exists and is still fresh, the callback is skipped and the cached value is returned immediately.
When the callback runs successfully, its return value is:
- serialised and written to the cache directory
- returned to the caller
That means the callback should always return a value that PHP can serialise safely.
If generating a replacement value fails, the callback can throw GT\FileCache\CacheValueGenerationException:
use GT\FileCache\CacheValueGenerationException;
$content = $cache->get("remote:feed", function():string {
$response = file_get_contents("https://example.com/feed");
if($response === false) {
throw new CacheValueGenerationException("Feed request failed");
}
return $response;
});When that exception is thrown during cache generation, FileCache returns null and does not write a replacement file.
Returning null from the callback is different from throwing CacheValueGenerationException.
$value = $cache->get("optional:value", fn() => null);In that case, null is written to the cache and treated as a normal cached value on later reads.
In practice, callbacks are easiest to reason about when they only fetch or compute the value and then return it. If the logic is more than a few lines, it is usually clearer to move it into a separate function or method and pass a callable reference.
$profile = $cache->get("user:105:profile", $userRepository->loadProfile(...));Next, move on to Cache invalidation for the cache lifetime model.
PHP.GT/FileCache is a separately maintained component of PHP.GT/WebEngine.