Skip to content

Type safety

Greg Bowler edited this page Jun 10, 2025 · 1 revision

The FileCache system provides the type-agnostic get() function - it returns whatever data was originally cached, with no assumptions or type conversions - but there are also type-safe accessor methods that validate or cast the returned data as needed.

Basic getter (not type safe)

$value = $cache->get("username", fn() => "guest");

This call will return exactly what was cached (or computed via the fallback callback). If you expect a string but the cached value turns out to be an array, you won't get an error = you'll just get the array, so your code will need to validate its own data when using the get function.

Type safe getters

To enforce type safety, FileCache offers the following typed accessors:

  • getString(string $name, callable $callback)
  • getInt(string $name, callable $callback)
  • getFloat(string $name, callable $callback)
  • getBool(string $name, callable $callback)
  • getDateTime(string $name, callable $callback) - returns a DateTimeInterface by either unserialising a class, using a date string, or using a unix timestamp.
  • getArray(string $name, callable $callback) - returns an array (note that this function does not ensure the type of the array contents)
  • getInstance(string $name, class-string $className, callable $callback) - ensures the cached value is an instance of a given class, or scalar type
  • getTypedArray(string $name, class-string $className, callable $callback)

These methods either cast values or throw a TypeError when the conversion isn't valid. This ensures that the cache doesn't silently corrupt your application's expectations.

Example: getInt

$visitCount = $cache->getInt("visit-count", fn() => 0);

Even if the original value is a string like "105", this will safely return the integer 105. If the value is not numeric (e.g. "One hundred and five"), a TypeError will be thrown.

Example: getTypedArray

You can also validate arrays at a more granular level:

$files = $cache->getTypedArray("fileList", SplFileInfo::class, fn() => []);

This will validate that every element in the array is an instance of SplFileInfo. If even one element is not, a TypeError will be thrown.

This also supports scalar types:

$ids = $cache->getTypedArray("user-ids", "int", fn() => []);

In all of the examples above, a stubbed callback is used (e.g. fn() => []) to simulate a cache miss and provide a default value. This callback is only invoked if no valid cached value exists. While this makes the examples easier to read in isolation, it's worth noting that these callbacks play a critical role in how the FileCache system lazily populates its entries. In the next section, we'll take a closer look at callback handling.

Clone this wiki locally