Skip to content

Getting started

Greg Bowler edited this page May 4, 2026 · 1 revision

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.

1. Install the package

composer require phpgt/typesafegetter

2. Implement TypeSafeGetter

The 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.

3. Read scalar values

$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")); // null

4. Read dates

getDateTime() accepts:

  • a DateTimeInterface object
  • 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);

5. Read object instances

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.

Clone this wiki locally