|
Object serialization is the process fo converting an object into a string representation of the object.
This process has man applications but one of the main applications I use it for is the tracking of user information across different pages and or shopping cart information.
Imagine this situation. You are required to print the users name across all the pages they visit. Obviously you hit the database and store the information inside your user object. A class for this would look saomething like:
class User{
private $firstName;
private $lastName;
private $email;
private $username;
private $password;
public function __construct($username, $password){
// retrieve user info and assign to properties of class
}
//class accessors etc
}
$oUser = new User("fred","barney");
Now you have all the user info in one object. What you might be tempted to do is something like this:
sessions_start();
$_SESSION['username'] = $oUser->getUsername();
$_SESSION['password'] = $oUser->getPassword();
$_SESSION['firstName'] = $oUser->getFirstName();
$_SESSION['lastName'] = $oUser->getLastName();
session_write_cloase();
Now every other page using these variables you have to go
session_start();
$username = $_SESSION['username'];
$password = $_SESSION['password'];
$firstName = $_SESSION['firstName'];
$lastName = $_SESSION['lastName'];
You have to keep track of four different keys using this method and would have to instantiate a new instance of the user object on eveyr page. Now imagine your user belonged to a group. Now you have to track, at a minimum, the group id. This means you have to add a new key and execute and SQL query evertime you want to retreive the group details.
Now watch how object serialization cleans this up
$oUser = new User("fred","barney");
session_start();
$_SESSION['user'] = serialize($oUser);
session_write_close()
Now the object has been serialized in the $_SESSION['user'] index. To access the object again is just as simple.
session_start();
$oUser = unserialize($_SESSION['user']);
session_write_close();
Now you have a fully fledged user object and you can access all the methods inside it
echo $oUser->getFirstName() . " " . $oUser->getLastName();
What is even better is if you have objects inside you class these objects are available as well. Say the user class has a group object inside it. You can access the group object as well.
echo $oUser->getGroup()->Name();
Pretty cool huh? I am sure you can see the endless applications this little trick has. One noticable application is the creation of a state environment in a stateless environment.
Happy coding!
|