-
-
Notifications
You must be signed in to change notification settings - Fork 1
Type safe getters
Session and SessionStore both implement Gt\TypeSafeGetter\TypeSafeGetter.
That gives us a consistent way to read common types without manually casting every value. The same getter style is used across several PHP.GT libraries.
get(string $name):mixedgetString(string $name):?stringgetInt(string $name):?intgetFloat(string $name):?floatgetBool(string $name):?boolgetDateTime(string $name):?DateTimeInterfacegetInstance(string $name, string $className)
$session->set("auth.userId", "42");
$session->set("basket.total", "12.50");
$session->set("ui.compact", "1");
$userId = $session->getInt("auth.userId");
$total = $session->getFloat("basket.total");
$compact = $session->getBool("ui.compact");If the value is missing, the typed getter returns null.
If the value exists, scalar getters cast to the requested PHP type.
getDateTime() accepts values that can be turned into a DateTimeImmutable.
$session->set("auth.lastSeen", "2026-04-23 10:15:00");
$lastSeen = $session->getDateTime("auth.lastSeen");
echo $lastSeen?->format("j F Y");Numeric values are treated as Unix timestamps.
getInstance() checks that a stored object is an instance of the class or interface we ask for.
$basket = $session->getInstance("checkout.basket", Basket::class);If the stored value is the wrong object type, a TypeError is thrown. This is intentional: it catches session-shape mistakes close to where they are read.
It is usually best to use typed getters as soon as session data enters application logic:
function do_save(Session $session, ProfileRepository $profiles):void {
$userId = $session->getInt("auth.userId");
if(!$userId) {
throw new RuntimeException("You must be signed in to save a profile.");
}
$profiles->saveForUser($userId);
}That keeps the rest of the function working with known types.
Next, look at the browser cookie and PHP options in Session cookies and configuration.
phpgt/session is a separately maintained component of PHP.GT/WebEngine.