-
-
Notifications
You must be signed in to change notification settings - Fork 0
Type safety
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.
get(string $name, callable $callback):mixedgetString(string $name, callable $callback):stringgetInt(string $name, callable $callback):intgetFloat(string $name, callable $callback):floatgetBool(string $name, callable $callback):boolgetDateTime(string $name, callable $callback):DateTimeInterfacegetArray(string $name, callable $callback):arraygetTypedArray(string $name, string $className, callable $callback):arraygetInstance(string $name, string $className, callable $callback):object
$value = $cache->get("username", fn() => "guest");This method is useful when the calling code already knows how to handle the cached value.
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.
getDateTime() accepts several common cached forms:
- an existing
DateTimeInterfaceinstance - 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.
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.
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.
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.
PHP.GT/FileCache is a separately maintained component of PHP.GT/WebEngine.