The Basics of Serializing Objects in PHP

Object serialization in PHP is very easy, and can be used for a variety of different purposes. It can be used to perform some fairly complex operations, in fact. This article, the first of a three-part series, introduces you to object serialization and a number of the tasks for which you can put this approach to use.

Introduction

Anyone who has been using PHP object-oriented programming for a while knows that object serialization can be a useful approach, which can be utilized for different purposes. Whether certain objects need to be stored as a string representation of their methods and properties in a database table, or maintained “alive” across several HTTP requests via a session mechanism, in all these cases serialization, and its counterpart, unserialization, play an undoubtedly relevant role.

Certainly one of the best things about serializing objects is its extreme ease to perform, trust me. Using the popular combination of “serialize()/unserialize()” PHP native functions, it is perfectly possible to get an object serialized and vice versa, during the execution of a PHP application, without the need to appeal to sophisticated programming techniques.

The truth is that when it comes to serializing objects, PHP makes the whole process a no-brainer task. However, despite its ease, object serialization can be used in different situations, in order to perform more complex operations, such as making an object persist during different web pages, or taking advantage of the “__sleep()” and “__wakeup()” magic functions, which are called automatically when an object is serialized and unserialized respectively.

As you can see, serializing objects in PHP is a very useful approach, which deserves at least a closer analysis. That’s why over the course of this three-part series,  I’ll take an in-depth look at the more relevant topics regarding the serialization of objects, starting out with the basics, and progressively introducing more advanced concepts, like using objects in sessions, and storing them in database tables.

What should you expect from this series? By the end of it, you should be equipped with a decent knowledge of how to serialize/unserialize objects without losing their methods and properties during the transition, as well as constructing persisting and session objects, and much more.

Having established the goals for this series, let’s introduce ourselves to the vast territory of object serialization in PHP. Let’s go!

{mospagebreak title=Explaining the core concepts}

In order to illustrate how an object, that is converted to a byte-stream representation of its methods and properties, can be serialized, I’ll set up a concrete example that will show the complete sequence for serializing/unserializing the object in question.

Of course, before any attempt is made to serialize an object, I should define a class from which I can create different instances. Thus, here is a sample PHP class named “DataSaver,” which is simply tasked with saving an input string to a given text file. This class looks like this:

class DataSaver{
    var $data;
    var $fileDir;
    function DataSaver($data){
        if(!is_string($data)){
            trigger_error(‘Invalid data type’,E_USER_ERROR);
        }
        $this->data=$data;
        $this->fileDir=’defaultDir';
    }
    // save data to file
    function save(){
        if(!$fp=fopen($this->fileDir.’/data.txt’,’w’)){
            trigger_error(‘Error opening data
file’,E_USER_ERROR);
        }
        fwrite($fp,$this->data);
        fclose($fp);
    }
    // fetch data from file
    function fetch(){
        if(!$contents=file_get_contents($this-
>fileDir.’/data.txt’)){
            trigger_error(‘Error opening data
file’,E_USER_ERROR);
        }
        return $contents;
    }
}

In this case, the class listed above accepts as an incoming argument a string, which can be saved to a specific file and then retrieved at a later time, by using the “save()” and “fetch()” methods respectively. Now, pay attention to the following snippet, where an instance of the “DataSaver” class is serialized, and in turn restored to its original state:

// instantiate ‘datasaver’ object
$dataSaver=&new DataSaver(‘This string will be saved to file’);
// save data to file
$dataSaver->save();
// display sample data
echo $dataSaver->fetch().'<br />';
// serialize object
$dataObj=serialize($dataSaver);
$dataObj=unserialize($dataObj);
// call object methods after unserializing object
echo $dataObj->fetch();

As you can see, the above example shows a few interesting things. Notice how after instantiating a “DataSaver” object, and calling its “save()” and fetch()” methods, this object is serialized and next unserialized through the corresponding “serialize()/unserialize()” functions.

Of course, the most important thing regarding the previous example consists of emphasizing how the object can be restored to its original state, which means that all its methods can be called as expected. The following lines clearly illustrate this concept:

// serialize object
$dataObj=serialize($dataSaver);
$dataObj=unserialize($dataObj);
// call object methods after unserializing object
echo $dataObj->fetch();

The output of the above snippet is as follows:


This string will be saved to file

Certainly, the above example demonstrates the ease, offered by PHP, of serializing an object inside an application, as well as reversing the process and using the object’s methods and properties accordingly. This concept can be potentially very handy, particularly in situations where you need to save your objects at least temporally, and then retrieve them at a later time.

After showing the first example of how to serialize/unserialize an object, I hope you understand how the whole process works, as well as the possible implementations of this technique inside an application.

Now, it’s time to learn how to use serialization inside of objects, thus in order to learn more about this approach, please click on the link below.

{mospagebreak title=Creating self-serializing objects}

Having demonstrated how an object can be serialized from outside, the next step consists of showing how to create objects that are capable of serializing themselves. Sounds a little bit confusing? It isn’t. Study the following class based on the previous example, which has the ability to serialize itself:

class DataSaver{
    var $data;
    var $fileDir;
    function DataSaver($data){
        if(!is_string($data)){
            trigger_error(‘Invalid data type’,E_USER_ERROR);
        }
        $this->data=$data;
        $this->fileDir=’defaultDir';
    }
    // save data to file
    function save(){
        if(!$fp=fopen($this->fileDir.’/data.txt’,’w’)){
            trigger_error(‘Error opening data
file’,E_USER_ERROR);
        }
        fwrite($fp,$this->data);
        fclose($fp);
    }
    // fetch data from file
    function fetch(){
        if(!$contents=file_get_contents($this-
>fileDir.’/data.txt’)){
            trigger_error(‘Error opening data
file’,E_USER_ERROR);
        }
        return $contents;
    }
    function saveSerialized(){
        if(!$fp=fopen($this->fileDir.’/data.txt’,’w’)){
            trigger_error(‘Error opening data
file’,E_USER_ERROR);
        }
        fwrite($fp,serialize($this));
        fclose($fp);
    }
}

As shown above, now the “DataSaver” class has an additional method, aside from the ones you saw in the previous example. In this case, the “saveSerialized()” method takes up the object itself, then serializes it and finally saves it to the specified text file. Quite interesting, right?

An example that covers how to use this self-serializing feature is illustrated by the snippet below:

// instantiate ‘datasaver’ object
$dataSaver=&new DataSaver(‘This string will be saved to file’);
// save data to file
$dataSaver->save();
// save serialized object to file
$dataSaver->saveSerialized();

With reference to the capacity offered by the “saveSerialized()” method, all the objects that have the capability to serialize themselves are commonly called self-serializing objects, and generally are used as base objects for deriving other objects that persist during the execution of an application. But in fact, I’m getting ahead of myself. Read the next section of the article, where I’ll explain how to create objects that are capable of performing a serialization/unserialization sequence on themselves.

{mospagebreak title=Creating self-saving objects}

As you learned in the previous section, creating objects that serialize themselves is a fairly comprehensive process, since all you have to do is add to the corresponding class a method capable of saving the serialized object to a specified file, or in many cases, to a database table.

However, self-serializing objects are only provided with the ability to save themselves to a file, or whatever storage media you want to use. So, what if I tell you that it’s possible to create objects that not only serialize and save to a file themselves, but also are capable of performing a self-restoring process?

Actually, this kind of object is called a “self-saving” object, and the class defined below demonstrates how to create it. Take a look at its source code:

class ObjectSaver{
    var $objectFile;
    function ObjectSaver($objectFile=’defaultDir/objects.txt’){
        $this->objectFile=$objectFile;
        $this->save();
    }
    // save serialized object to file
    function save(){
        if(!$fp=fopen($this->objectFile,’w’)){
            trigger_error(‘Error opening object
file’,E_USER_ERROR);
        }
        if(!fwrite($fp,serialize($this))){
            trigger_error(‘Error writing data to object
file’,E_USER_ERROR);
        }
        fclose($fp);
    }
    // fetch object from file
    function fetch(){
        if(!$obj=unserialize(file_get_contents($this-
>objectFile))){
            trigger_error(‘Error fetching object from
file’,E_USER_ERROR);
        }
        return $obj;
    }
}

As you can see, the sample “ObjectSaver” class that I coded above shows a typical example of how to create an object that is capable of serializing and deserializing itself. In this case, whenever the object is instantiated, it will be serialized and saved to a text file, while in order to perform the reverse process, the “fetch()” method must be explicitly called.

To complement the concept of creating self-saving objects, the above class uses a simple text file both for storing the serialized object and restoring it back to its original state. Nevertheless, as I said before, you can use a database table for storing serialized objects, or even cookies, in case your application doesn’t demand huge storage requirements.

Now that you learned how to create self-saving objects based on the “ObjectSaver” class that I defined previously, take a look at the following example, which demonstrates how to use these objects:

// instantiate ‘objectsaver’ object
$objSaver=&new ObjectSaver();
// fetch unserialized object
$newObj=$objSaver->fetch();

As illustrated above, after a new “ObjectSaver” object has been instantiated, its “fetch()” method is called explicitly, in order to unserialize the object and store it in the “$newObj” variable.

After studying the previous example, perhaps you’re wondering…what’s the point of restoring the object to its original state, when it was already available at the time of being instantiated? Well, in fact this makes a lot of sense if you take into account that the respective “fetch()” method might be modified, let’s say for returning not the entire object, but only one specific property (or a set of properties), which should persist across different web pages. Doing so, you’ll be heading directly toward the concept of a “persistent” object, by the way a topic that I’ll cover in the second tutorial.

For now, be patient and have some fun experimenting with the previous “ObjectSaver” class, which can be slightly modified to display a trivial message, when the “fetch()” method is called appropriately.

Considering this small change, the modified version of the “ObjectSaver” class would look like this:

class ObjectSaver{
    var $objectFile;
    function ObjectSaver($objectFile=’defaultDir/objects.txt’){
        $this->objectFile=$objectFile;
        $this->save();
    }
    // save serialized object to file
    function save(){
        if(!$fp=fopen($this->objectFile,’w’)){
            trigger_error(‘Error opening object file’,E_USER_ERROR);
        }
        if(!fwrite($fp,serialize($this))){
            trigger_error(‘Error writing data to object
file’,E_USER_ERROR);
        }
        fclose($fp);
    }
    // fetch object from file
    function fetch(){
        if(!$obj=unserialize(file_get_contents($this-
>objectFile))){
            trigger_error(‘Error fetching object from
file’,E_USER_ERROR);
        }
        return $obj;
    }
    // display message
    function displayMessage(){
        return ‘This is an object that saves and retrieves itself
via its methods!';
    }
}

And eventually, an “ObjectSaver” object could be used as follows:

$objSaver=&new ObjectSaver();
$newObj=$objSaver->fetch();
echo $newObj->displayMessage();

In accordance with the above snippet, its output would be as follows:

This is an object that saves and retrieves itself via its
methods!

As you can see, the object in question unserializes itself and displays the corresponding sample message, which demonstrates that the “fetch()” method restores the object to its original state after being saved to the specified file by the “save()” method. Isn’t object serialization a fairly comprehensive process?

To wrap up

In this first part of the series, hopefully you learned the basics of object serialization in PHP, including some interesting concepts, like creating objects that are capable of saving and retrieving themselves through their own methods.

Over the course of the second article, I’ll explain how to create persisting objects, in addition to implementing the magic “__sleep()” and “__wakeup()” functions. As usual, see you in the next part!

[gp-comments width="770" linklove="off" ]

chat sex hikayeleri Ensest hikaye