Skip to content

Quick start guide

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

In this guide we will build the smallest useful standalone session setup.

In WebEngine applications, this setup is already done for us. The guide is still useful because it shows the shape of the objects that WebEngine provides.

1. Install the package

composer require phpgt/session

2. Create a session handler

The handler controls where the session data is stored.

use GT\Session\FileHandler;

$handler = new FileHandler();

FileHandler stores session data as files under the configured save path. If shared storage across multiple application servers is needed, use Redis session storage instead.

3. Create the session

use GT\Session\Session;

$session = new Session($handler, [
	"name" => "GT",
	"save_path" => "phpgt/session",
]);

When the save path is not an absolute path, the library places it under the system temporary directory. On many systems, the example above becomes something like /tmp/phpgt/session/GT.

4. Write values

$session->set("auth.userId", 105);
$session->set("auth.email", "cody@example.com");

Calling set() writes the value into the in-memory SessionStore, then immediately asks the handler to persist the session data.

5. Read values

if($session->contains("auth.userId")) {
	echo $session->getInt("auth.userId");
	echo $session->getString("auth.email");
}

The typed getters return null when the value does not exist. If a value does exist, it is converted to the requested type where possible.

6. Remove values

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

remove() can remove a single value, or a whole nested store when the key points to a store name.

7. Pass a smaller store to another object

use GT\Session\SessionStoreInterface;

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

	public function addItem(string $sku):void {
		$items = $this->session->get("items") ?? [];
		$items []= $sku;
		$this->session->set("items", $items);
	}
}

$basket = new Basket($session->getStore("basket", true));
$basket->addItem("TEA-001");

The Basket class only receives the basket store. It does not need to know about auth, flash messages, or any other session data.

Note

In WebEngine, GT\Session\Session is injected into page logic from the service container. We usually start from function go(Session $session):void or function do_save(Session $session):void, rather than constructing it ourselves.


Next, see the constructor and setup options in Constructing a Session.

Clone this wiki locally