Complex Objects In PHP Sessions

So you’ve discovered the power of using sessions to store persistent data. Perhaps you have a user logging into your site, and are able to store various preferences about them. Now, however, you want to get a little more sophisticated with your code and break into some of that crazy object oriented stuff! Well if you do you’ll probably think at some point, “Hey, let’s see if I can store that in a session so I don’t have to query for it every time I need it!” Good call, but there are a couple of caveats that you must consider. Let’s make an example, shall we?

For this example let us build a user object that will store a basic representation of a logged in user. For this purpose we will store their email address, first and last name, and a user ID. I am assuming you have the basic knowledge of using classes in PHP, and we are going to do this in PHP 5 format. Sorry PHP 4 folks. The OOP support just got so much better in five. Anyway, lets take a look at what this class may look like.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
class User
{
	protected $vars;
 
	public function __construct($UserId = 0)
	{
		$this->vars = array(
		"userId" => $UserId,
		"email" => "",
		"firstName" => "",
		"lastName" => ""
		);
	}
 
	public function __get($VarName)
	{
		if (isset($this->vars[$VarName])) return $this->vars[$VarName];
	}
 
	public function __set($VarName, $Value)
	{
		if (isset($this->vars[$VarName])) $this->vars[$VarName] = $Value;
	}
 
	public function __isset($VarName)
	{
		return isset($this->vars[$VarName]);
	}
}

There are a few things going on here. First and foremost we have made a class to represent a user, containing an ID, email address, first and last name. We’ve also used a little of PHP5’s special function magic to create getters and setters. Without going into the gory details the functions __get and __set allow you to create custom getter and setter functions. For more information on that coolness check out the PHP website’s section on overloading in classes. Ok, so we have a basic class. An example usage would be something to this effect.

1
2
3
4
$currentUser = new User(1);
$currentUser->email = "testUser@test.com";
$currentUser->firstName = "Test";
$currentUser->lastName = "User";

In this example we simple created a new instance of the class User and initialized it with a user ID of one (1). Onward to our purpose!

Now let’s say that you wish to store this object instance in your session for easy retrieval in the future. Why would you do this? One good reason is so that you won’t have to go back to a database for this user data every page request, and I’m sure you could find more reasons. Anyway… Here are the steps to storing this complex object in your session.

  1. If your class is in a seperate PHP file make sure it is included BEFORE you start your session. For that matter make sure you don’t have sessions auto starting in your INI file or configuration directives.
  2. Name and start your session. Not sure how to do that? See here.
  3. Check for the existance of your user object in the session.
  4. If it doesn’t exist, create the user object, then store it in the session. This requires you serializing the object prior to storage.
  5. If it does, unserialize it and retrieve it.

Sounds like a mouthful doesn’t it? Here’s a sample.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
session_name("storingComplexObjects");
session_start();
 
if (isset($_SESSION["loggedInUser"]))
{
	$currentUser = unserialize($_SESSION["loggedInUser"]);
	printf("User object is in session. Retrieving.<br />");
}
else
{
	$currentUser = new User(1);
	$currentUser->email = "testUser@test.com";
	$currentUser->firstName = "Test";
	$currentUser->lastName = "User";
 
	$_SESSION["loggedInUser"] = serialize($currentUser);
	printf("User object was not in session. Setting.<br />");
}
 
var_dump($currentUser);
echo "<br />";
var_dump($_SESSION);

In this example we first name and create the session. Then we are checking for the existance of a session variable named loggedInUser. If we have one, then we’ve already stored the user object and we need to retrieve it. The trick here for retrieving a complex object from the session is using the function unserialize. This function essentially converts a string representation of a complex object to its object format in memory, making it a userful instance of the User class.

If we do not have loggedInUser then we are creating a new instance of the User object, and then storing it in the session. The trick in this case is the function serialize. This function converts an object instance to a string representation suitable for storage in a session, database, or otherwise. You will notice that the first run of this code will output to the browser that we are having to create our session variable for the first time, but the second run shows us that it is already there, and that we simply need to retrieve it.

And there you have it! Happy coding!