Skip to content
Greg Bowler edited this page Jul 4, 2023 · 10 revisions

A session is a mechanism to temporarily store data for a particular user of an application, so the state can be maintained over multiple web requests. It's particularly useful to store the authentication state for the current user, or other transient information like the user's currently selected timezone, currency, language, etc.

HTTP itself does not allow for any state to be remembered between pages, so PHP sets a session cookie in the user's web browser so that requests from individual users can be identified on the server. The cookie is composed of a randomised string of letters and numbers called the session ID.

All session data should be seen as temporary. When the user's browser closes, the session ID is wiped - it's up to you to persist the data in some way permanently, if required, such as to a database or filesystem.

An object oriented session interface

Native PHP exposes all data stored to the session in the $_SESSION superglobal, which is readable and writable by any line of code in your project, or any line of code in any third party dependencies you rely on. For this reason, this repository enforces a major benefit of object oriented coding: encapsulation.

Encapsulation means that instead of all code having full access to the session data, it's your job as the developer to decide what areas of code have access to the data stored in the session. This repository also introduces a way to namespace session data, so certain areas of code can only read/write one subset of the session data.

An example of what using PHP.Gt/Session looks like in your PHP:

function example(Session $session):void {
// Access session data using dot notation:
	if($username = $session->getString("auth.username")) {
		welcome_user($username);
	}
	else {
// Encapsulate a namespaced session store to the login area:
		login($session->getStore("auth", true));
	}
}

It's possible to protect against usage of superglobal variables, meaning access to $_SESSION is prohibited. This is the default behaviour in WebEngine applications.


To get started, learn about type safety.