Skip to content

Callback handling

Greg Bowler edited this page Jun 11, 2025 · 2 revisions

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.

Caching the result

When the callback is executed, its return value is:

  1. Stored on disk using the configured cache mechanism (typically handled automatically via FileAccess),
  2. Optionally validated against the expected type (for typed getters),
  3. Returned directly to your code.

Future calls to get*() for the same key will bypass the callback, only using the cached result.

Return type consistency

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

Pure functions are encouraged

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.

Use function references for tidy code

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.

Clone this wiki locally