Home arrow PHP arrow Page 4 - The Basics of Serializing Objects in PHP

Creating self-saving objects - 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.

TABLE OF CONTENTS:
  1. The Basics of Serializing Objects in PHP
  2. Explaining the core concepts
  3. Creating self-serializing objects
  4. Creating self-saving objects
By: Alejandro Gervasio
Rating: starstarstarstarstar / 46
June 06, 2006

print this article
SEARCH DEV SHED

TOOLS YOU CAN USE

advertisement

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!



 
 
>>> More PHP Articles          >>> More By Alejandro Gervasio
 

blog comments powered by Disqus
escort Bursa Bursa escort Antalya eskort
   

PHP ARTICLES

- Hackers Compromise PHP Sites to Launch Attac...
- Red Hat, Zend Form OpenShift PaaS Alliance
- PHP IDE News
- BCD, Zend Extend PHP Partnership
- PHP FAQ Highlight
- PHP Creator Didn't Set Out to Create a Langu...
- PHP Trends Revealed in Zend Study
- PHP: Best Methods for Running Scheduled Jobs
- PHP Array Functions: array_change_key_case
- PHP array_combine Function
- PHP array_chunk Function
- PHP Closures as View Helpers: Lazy-Loading F...
- Using PHP Closures as View Helpers
- PHP File and Operating System Program Execut...
- PHP: Effects of Wrapping Code in Class Const...

Developer Shed Affiliates

 


Dev Shed Tutorial Topics: