PHP
  Home arrow PHP arrow Page 4 - The Basics of Serializing Objects in PHP
Dev Shed Forums  
Administration  
AJAX  
Apache  
BrainDump  
DHTML  
Flash  
Java  
JavaScript  
Multimedia  
MySQL  
Oracle  
Perl  
PHP  
Practices  
Python  
Reviews  
Security  
Smartphone Development  
Style-Sheets  
Web Services  
XML  
Zend  
Zope  
Mobile Linux  
App Generation ROI  
IBM® developerWorks  
Forums Sitemap  
E-Commerce Hosting  
Linux Web Hosting  
Managed Hosting  
Small Business Hosting  
VPS Hosting  
Weekly Newsletter

 
Developer Updates  
Free Website Content 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us Get Paid  
Request Media Kit
Contact Us  
Site Map  
Privacy Policy  
Support  
 USERNAME
 
 PASSWORD
 
 
  >>> SIGN UP!  
  Lost Password? 
Google.com  
PHP

The Basics of Serializing Objects in PHP
By: Alejandro Gervasio
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: starstarstarstarstar / 36
    2006-06-06


    Table of Contents:
  • The Basics of Serializing Objects in PHP
  • Explaining the core concepts
  • Creating self-serializing objects
  • Creating self-saving objects

  • Rate this Article: Poor Best 
      ADD THIS ARTICLE TO:
      error-file:tidyout.log Del.ici.ous error-file:tidyout.log Digg
      error-file:tidyout.log Blink error-file:tidyout.log Simpy
      error-file:tidyout.log Google error-file:tidyout.log Spurl
      error-file:tidyout.log Y! MyWeb error-file:tidyout.log Furl
    Email Me Similar Content When Posted
    Add Developer Shed Article Feed To Your Site
    Email Article To Friend
    Print Version Of Article
    PDF Version Of Article

     
     
    ADVERTISEMENT


    The Basics of Serializing Objects in PHP - Creating self-saving objects
    ( Page 4 of 4 )

    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
     

       

    PHP ARTICLES

    - Implementing Factory Methods in PHP 5
    - Merging a File Split for FTP Upload using PHP
    - Getting Data from Yahoo Site Explorer Inboun...
    - Method Chaining: Adding More Selecting Metho...
    - How to Split a File During an FTP Upload Usi...
    - Expanding a Custom CodeIgniter Library with ...
    - Using the Yahoo Site Explorer Inbound Links ...
    - Building a CodeIgniter Custom Library with M...
    - Building an E-mini Trading System Using PHP ...
    - Completing the MySQL Class with Method Chain...
    - Building Dynamic Queries with Chainable Meth...
    - PHP Encryption and Decryption Methods
    - Building a MySQL Abstraction Class with Meth...
    - Completing a Sample String Processor with Me...
    - Mastering WHILE Loops for PHP and MySQL





    © 2003-2009 by Developer Shed. All rights reserved. DS Cluster 3 Hosted by Hostway
    For more Enterprise Application Development news, visit eWeek