-
-
Notifications
You must be signed in to change notification settings - Fork 2
Namespaces
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.
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.
Php.Gt/Session is a separately maintained component of PHP.Gt/WebEngine