-
-
Notifications
You must be signed in to change notification settings - Fork 1
Callback handling
When retrieving a value from the cache using any get*()
method, you're required to provide a callback. This is a core concept in FileCache
- if there is valid data in the cache, the callback will be skipped, and the data will be loaded from the cache. Only when there is no valid data in the cache will the callback execute, which will perform the work required to refresh the cache.
$value = $cache->get("example-key", someExpensiveOperation(...));
If there is valid data in the example-key
cache, it will be returned, otherwise someExpensiveOperation()
will be called.
When the callback is executed, its return value is:
- Stored on disk using the configured cache mechanism (typically handled automatically via
FileAccess
), - Optionally validated against the expected type (for typed getters),
- Returned directly to your code.
Future calls to get*()
for the same key will bypass the callback, only using the cached result.
When using a type-safe getter like getInt()
or getTypedArray()
, the return value of the callback must match the expected type. If it doesn't, a TypeError
will be thrown.
$cache->getInt("count", fn() => "zero"); // ❌ Throws TypeError
Because callbacks are evaluated only once per cache key, they should ideally be pure: deterministic, free of side effects, and safe to run only once. Avoid callbacks that rely on global state or mutate external data.
if the work that needs to be done to load the content is going to take time to load, it's probably going to be more than a couple of lines of code. Therefore, it would be beneficial to maintain the callback function in its own separate function or separate class.
Rather than implementing the callback function inline, you can use PHP's first class callable syntax to reference an external function.
$cache->get("user-profile", $userRepository->getProfile(...));
By separating cache retrieval from value generation, FileCache lets you express fallback logic cleanly and efficiently within your code. In the next section, we'll explore what happens when data becomes outdated in cache invalidation.
PHP.GT/FileCache is a separately maintained component of PHP.GT/WebEngine.