Skip to content

Session stores and namespaces

Greg Bowler edited this page Apr 23, 2026 · 1 revision

SessionStore is the object that actually holds session values.

The root Session object delegates reads and writes to a root store. Nested stores can then represent separate areas of the session, such as auth, basket, ui, or csrf.

Dot notation

Keys can contain dots. Everything before the final dot is treated as a store path, and the final part is the value name.

$session->set("user.name", "Cody");
$session->set("user.colour", "orange");

That creates a user store with two values:

  • name
  • colour

We can read those values with the same dot notation:

echo $session->getString("user.name");

Creating a store

getStore() returns a SessionStoreInterface when the store exists.

$authStore = $session->getStore("auth");

If the store might not exist yet, pass true as the second argument:

$authStore = $session->getStore("auth", true);

That pattern is common when constructing a class that owns one area of session data.

Passing a store to another class

use GT\Session\SessionStoreInterface;

class AuthSession {
	public function __construct(
		private SessionStoreInterface $session
	) {}

	public function signIn(int $userId):void {
		$this->session->set("userId", $userId);
	}

	public function getUserId():?int {
		return $this->session->getInt("userId");
	}
}

$auth = new AuthSession($session->getStore("auth", true));

Inside AuthSession, the key is just userId. The class does not need to know that the value is stored at auth.userId in the full session.

This is the core encapsulation benefit: each part of the application receives only the session area it owns.

Nested stores

Stores can be nested more than one level deep.

$session->set("checkout.payment.lastMethod", "card");

$paymentStore = $session->getStore("checkout.payment");
echo $paymentStore->getString("lastMethod");

Nested stores are useful when one larger area of the application has smaller sub-areas.

Removing data

Remove a single value:

$session->remove("auth.userId");

Remove a nested store:

$session->remove("checkout.payment");

Calling remove() on a SessionStore without an argument removes that store from its parent.

$basket = $session->getStore("basket");
$basket?->remove();

Writing behaviour

set() and remove() both call write() after changing the store. write() serialises the root store and asks the configured handler to persist it.

If we store an object in the session, PHP must be able to autoload that object's class before the session data is read back.


Next, see how to read values predictably with Type-safe getters.

Clone this wiki locally