Skip to content

Type safety

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

GT\FileCache\Cache exposes one untyped getter and several typed getters.

The untyped get() method returns whatever value was cached. The typed methods either cast, convert, or validate the cached value before returning it.

The available getters

  • get(string $name, callable $callback):mixed
  • getString(string $name, callable $callback):string
  • getInt(string $name, callable $callback):int
  • getFloat(string $name, callable $callback):float
  • getBool(string $name, callable $callback):bool
  • getDateTime(string $name, callable $callback):DateTimeInterface
  • getArray(string $name, callable $callback):array
  • getTypedArray(string $name, string $className, callable $callback):array
  • getInstance(string $name, string $className, callable $callback):object

Basic getter

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

This method is useful when the calling code already knows how to handle the cached value.

Scalar getters

getString(), getInt(), getFloat(), and getBool() follow PHP's normal scalar casting behaviour:

$count = $cache->getInt("visits", fn() => "105"); // String "105" will be cast to int `105`.
$enabled = $cache->getBool("feature-flag", fn() => "1"); // String "1" will be cast to `true`

That means these methods do not perform strict validation. If the cached value can be cast by PHP, the cast result is returned.

Date and time getter

getDateTime() accepts several common cached forms:

  • an existing DateTimeInterface instance
  • an integer Unix timestamp
  • a string accepted by DateTimeImmutable
$publishedAt = $cache->getDateTime("article:publishedAt", fn() => "2026-04-19 09:30:00");

The return value is always a DateTimeInterface.

Array getter

getArray() only checks that the cached value is an array:

$config = $cache->getArray("app:config", fn() => ["debug" => false]);

If the cached value is not an array, a TypeError is thrown.

Typed arrays

getTypedArray() validates every value in the array and returns a converted array of the requested type:

$ids = $cache->getTypedArray("user:ids", "int", fn() => ["1", 2, 3.0]);
$files = $cache->getTypedArray("files", SplFileInfo::class, fn() => []);

The supported scalar type names are:

  • "int" or "integer"
  • "float" or "double"
  • "string"
  • "bool" or "boolean"

We can also pass a class name to require every element to be an instance of that class.

If any element cannot be converted or validated, a TypeError is thrown.

Single object instances

getInstance() ensures that the cached value is an instance of the class we ask for:

$file = $cache->getInstance("report:file", SplFileInfo::class, function():SplFileInfo {
	return new SplFileInfo("/tmp/report.txt");
});

Now move on to Callback handling to see when the callback runs and how cache population failures are handled.

Clone this wiki locally