-
-
Notifications
You must be signed in to change notification settings - Fork 1
Quick start guide
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.
composer require phpgt/sessionThe 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.
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.
$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.
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.
$session->remove("auth.email");remove() can remove a single value, or a whole nested store when the key points to a store name.
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.
phpgt/session is a separately maintained component of PHP.GT/WebEngine.