Working with MySQL and Sessions to Serialize Objects in PHP - Another implementation of object serialization: saving objects to MySQL tables
(Page 4 of 5 )
As I said before, the last example I’m going to show you illustrates the entire process for storing serialized objects in a MySQL table. To begin with, I’ll define a simple “objects” database table, composed of “id” and “users” fields, which will house the IDs of stored objects and their serialized structure. Here is the SQL statement that creates this table:
CREATE TABLE objects (
id INT(4) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
users TEXT NOT NULL
);
As you can see, the table for storing serialized objects is fairly simple, thus now I’m going to build a basic “User” class, which will store some data about fictional people, such as Name, Postal Address and Email. The signature of the class looks like this:
// define 'User' class
class User{
var $name;
var $address;
var $email;
function User($userData=array()){
if(!is_array($userData)){
trigger_error('User data must be an
array!',E_USER_ERROR);
}
foreach($userData as $property=>$value){
if($property==''||$value==''){
trigger_error('Invalid values for user
data!',E_USER_ERROR);
}
$this->{$property}=$value;
}
}
// obtain user name
function getName(){
return $this->name;
}
// obtain user address
function getAddress(){
return $this->address;
}
// obtain user email
function getEmail(){
return $this->email;
}
}
That’s it. Now I defined the corresponding “User” class, which will serve to spawn as many objects as required, and after being serialized, these objects will be stored in the “objects” sample table.
There’s still one more thing that I wish to do before proceeding to store objects in a MySQL table: I’ll create an object serializing class, in order to handle the complete serialize/unserialize process by using its interface. The source code of this class, which I called “ObjectSerializer”, is shown below:
class ObjectSerializer{
function ObjectSerializer(){}
function getSerializedObj($obj){
if(!is_object($obj)){
trigger_error($obj.'input parameter must be an
object!',E_USER_ERROR);
}
return serialize($obj);
}
function getUnserializedObj($data){
if(!is_string($data)){
trigger_error($data. 'must be a
string!',E_USER_ERROR);
}
return unserialize($data);
}
}
In this case, the above class was defined as a simple wrapper for the pair of “serialize()/unserialize()” PHP functions, so it does not require much discussion about how it works. Given that, the next step consists of populating the “objects” table with some users, so first I’ll proceed to create them, like this:
// instantiate some 'User' objects
$usr1=&new User(array('name'=>'John Doe','address'=>'5456
Protocol Avenue MA','email'=>'john@domain.com'));
$usr2=&new User(array('name'=>'Susan Smith','address'=>'12345 Web
Boulevard CA','email'=>'susan@domain.com'));
$usr3=&new User(array('name'=>'Jeff Williams','address'=>'154321
Hyperlink Road NV','email'=>'jeff@domain.com'));
$usr4=&new User(array('name'=>'Bridget Lopez','address'=>'13579
Socket Street NY','email'=>'bridget@domain.com'));
All right, now that some fictional users have been created, it’s time to serialize them and store them in the “objects” database table. To do this, I’ll use a couple of MySQL wrapper classes that will be listed at the end of the example. Here is how the entire set of “Users” objects are stored in the corresponding table:
// connect to MySQL
$db=&new MySQL(array('host'=>'host','user'=>'user','password'=>'pass',
'database'=>'database'));
// instantiate 'ObjectSerializer' object
$objSer=&new ObjectSerializer();
// insert objects into database table
$db->query("INSERT INTO objects (id,users) VALUES
(NULL,'".$objSer->getSerializedObj($usr1)."')");
$db->query("INSERT INTO objects (id,users) VALUES
(NULL,'".$objSer->getSerializedObj($usr2)."')");
$db->query("INSERT INTO objects (id,users) VALUES
(NULL,'".$objSer->getSerializedObj($usr3)."')");
$db->query("INSERT INTO objects (id,users) VALUES
(NULL,'".$objSer->getSerializedObj($usr4)."')");
As you can see, the above script first connects to MySQL, then instantiates a new “ObjectSerializer” object, and finally inserts all the serialized “User” objects into the sample “objects” database table. Definitely, you’ll agree with me that this step is simple and comprehensive.
Once the respective users have been stored, I’m going to reverse the process and fetch the objects from the respective table, so I’m able to use their methods to display the information attached to them. Take a look at the piece of code below that precisely demonstrates how the objects are restored:
// restore objects from database table
$result=$db->query("SELECT * from objects");
while($row=$result->fetchRow()){
$obj=$objSer->getUnserializedObj($row['users']);
echo 'ID: '. $row['id'].' Name: '.$obj->getName().' Postal
Address: '.$obj->getAddress().' Email: '.$obj->getEmail().'<br />';
}
In this case, objects are first fetched from the database table by using a regular SELECT statement, and then unserialized by the “getUnserializedObj()” method. Finally, the data associated with each user is displayed by calling each of the corresponding getters.
Of course, below I listed the output generated by the previous example:
ID: 1 Name: John Doe Postal Address: 5456 Protocol Avenue MA Email: john@domain.com
ID: 2 Name: Susan Smith Postal Address: 12345 Web Boulevard CA Email: susan@domain.com
ID: 3 Name: Jeff Williams Postal Address: 154321 Hyperlink Road NV Email: jeff@domain.com
ID: 4 Name: Bridget Lopez Postal Address: 13579 Socket Street NY Email: bridget@domain.com
Even when you’re usually storing your binary objects in BLOB table fields, the approach that I just showed you before can be considered a useful alternative for saving objects as plain strings.
Next: The complete list of classes for the example >>
More PHP Articles
More By Alejandro Gervasio