Skip to content

Callback handling

Greg Bowler edited this page Apr 19, 2026 · 3 revisions

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));

When the callback runs

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.

What happens to the return value

When the callback runs successfully, its return value is:

  1. serialised and written to the cache directory
  2. returned to the caller

That means the callback should always return a value that PHP can serialise safely.

Handling generation failures

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.

null is still a valid cached value

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.

Keep callbacks focused

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.

Clone this wiki locally