-
-
Notifications
You must be signed in to change notification settings - Fork 0
Typed methods
Once a class implements get(), the NullableTypeSafeGetter trait provides the rest of the public API.
public function get(string $name):mixed;This is the raw lookup method. It returns whatever the underlying store contains, or null when the key is missing.
The trait uses this method internally for all typed lookups.
These methods cast non-null values using PHP's normal scalar casting rules:
getString(string $name): ?stringgetInt(string $name): ?intgetFloat(string $name): ?floatgetBool(string $name): ?bool
Example:
$store = new KeyValueStore([
"intString" => "105",
"price" => "19.99",
"enabled" => "1",
]);
echo $store->getInt("intString");
echo $store->getFloat("price");
var_dump($store->getBool("enabled"));If the key is missing, each method returns null.
public function getDateTime(string $name): ?DateTimeInterface;This method handles three cases:
- if the stored value is already a
DateTimeInterface, it is returned as-is - if the stored value is numeric, it is treated as a Unix timestamp
- otherwise the value is passed to
DateTimeImmutable
Example:
$store = new KeyValueStore([
"published" => 1714550400,
]);
echo $store->getDateTime("published")?->format("Y-m-d");public function getInstance(string $name, string $className);Use this when the stored value should already be an object instance.
$store = new KeyValueStore([
"date" => new DateTimeImmutable("2024-05-01"),
]);
$date = $store->getInstance("date", DateTimeInterface::class);If the key is missing, null is returned.
If the value exists but is not an instance of the requested class or interface, a TypeError is thrown.
This is useful when the storage contains mixed values but a particular key is expected to hold one object type.
Use get() when:
- the value is not one of the common built-in scalar or date types
- you want to handle conversion yourself
- the value may be an array or another mixed structure
Use the typed methods when:
- the underlying data source stores strings that need casting
- you want a consistent
nullresult for missing keys - you want the calling code to be explicit about the expected type
Finally, see how values from Callbacks can be implemented.