-
-
Notifications
You must be signed in to change notification settings - Fork 0
Getting started
In this section we will build the smallest useful implementation of TypeSafeGetter.
Note
In WebEngine, you will usually use these methods through another package such as Input, Session, Config, Http, or Database rather than wiring this package directly into page logic, and you'll never need to require the package yourself using Composer.
composer require phpgt/typesafegetterThe only method you must supply yourself is get().
use GT\TypeSafeGetter\NullableTypeSafeGetter;
use GT\TypeSafeGetter\TypeSafeGetter;
class KeyValueStore implements TypeSafeGetter {
use NullableTypeSafeGetter;
public function __construct(
private array $data = [],
) {}
public function get(string $name):mixed {
return $this->data[$name] ?? null;
}
}The trait adds the typed methods on top of whatever get() returns.
$store = new KeyValueStore([
"name" => "Cody",
"age" => "9",
"weight" => "5.16",
"microchip" => true,
]);
echo $store->getString("name");
echo $store->getInt("age");
echo $store->getFloat("weight");
var_dump($store->getBool("microchip"));Missing keys return null:
var_dump($store->getString("missing")); // nullgetDateTime() accepts:
- a
DateTimeInterfaceobject - a Unix timestamp
- a date/time string understood by
DateTimeImmutable
$store = new KeyValueStore([
"created" => "2024-05-01 09:15:00",
]);
echo $store->getDateTime("created")?->format(DateTimeInterface::ATOM);getInstance() is for values that are already objects.
$user = new stdClass();
$user->name = "Cody";
$store = new KeyValueStore([
"user" => $user,
]);
$loadedUser = $store->getInstance("user", stdClass::class);
echo $loadedUser?->name;This method does not construct a new object. It returns the stored object after checking that it matches the requested class or interface. This is useful for static analysis - your IDE will know the value type of the returned object from getInstance, so intellisense will work for dynamic object typing.
See a breakdown of all Typed methods.