Skip to content

Namespaces

Greg Bowler edited this page May 26, 2023 · 8 revisions

Encapsulation is an important concept in object-oriented programming, and it's just as important when it comes to managing session data in PHP. Essentially, encapsulation is about bundling related data together and hiding it from the rest of the system, unless explicitly required.

Session namespaces provide this level of data encapsulation within your PHP sessions. When you use a session namespace, you're storing related session data together in a distinct area within the session. For instance, you might create an 'auth' namespace to hold data related to the current user, or a 'ui' namespace to store information specific to the current user interface settings. By doing this, it is easier to manage data, it's more intuitive to know where specific data is stored, and most importantly, each namespaced area of the session can be passed to individual areas of the system, meaning one area of the application code can't accidentally read/write another area's session.

Using dots to separate namespaces

Any object or scalar value can be stored to the Session object via a string key. The key can contain dots, which is a shorthand method of storing data to a namespace.

For example, storing two data using the strings user.name and user.colour will automatically create a SessionStore called user with two keys, name and colour. In the following example, we set these two values to the session, and then pass an example AppClass object the session store.

function example(Session $session, AppClass $thing):void {
	$session->set("user.name", "Cody");
	$session->set("user.colour", "orange");

	$thing->handleUserData($session->getStore("user"));
}

In the next section, learn how namespaces can be used for encapsulating session data throughout a project.

Clone this wiki locally