-
-
Notifications
You must be signed in to change notification settings - Fork 0
Home
This library defines a small contract for reading named values as specific PHP types.
It contains:
-
TypeSafeGetter, an interface for objects that expose named values -
NullableTypeSafeGetter, a trait that implements the common typed getter methods -
CallbackTypeSafeGetter, an interface for callback-driven lookups
The library does not decide where values come from. That part is left to the class implementing get(). One class might read from an array, another from session storage, and another from HTTP data.
This package can be used on its own in any PHP project, but in practice it is often used by other PHP.GT packages rather than directly by application code.
For example, across PHP.GT you will come across these typed getter methods on objects such as:
- configuration containers
- session stores
- HTTP header collections
- form and query data wrappers
- database row objects
In WebEngine projects, that usually means you benefit from this package indirectly through those higher-level services.
use GT\TypeSafeGetter\NullableTypeSafeGetter;
use GT\TypeSafeGetter\TypeSafeGetter;
class UserData implements TypeSafeGetter {
use NullableTypeSafeGetter;
public function __construct(
private readonly array $data = [],
) {}
public function get(string $name):mixed {
return $this->data[$name] ?? null;
}
}
$user = new UserData([
"id" => "42",
"isAdmin" => 1,
"registered" => "2024-01-15 10:30:00",
]);
echo $user->getInt("id");
var_dump($user->getBool("isAdmin"));
echo $user->getDateTime("registered")?->format("Y-m-d");In this example, the class only needs to provide get(). The trait handles the common conversions for strings, integers, floats, booleans, dates, and object instances.
Install the library from scratch in Getting started