PHP
  Home arrow PHP arrow Page 3 - Using the Sleep and Wakeup Functions to Serialize 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? 
PHP

Using the Sleep and Wakeup Functions to Serialize Objects in PHP
By: Alejandro Gervasio
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: starstarstarstarstar / 7
    2006-06-13


    Table of Contents:
  • Using the Sleep and Wakeup Functions to Serialize Objects in PHP
  • A quick look at how to define self-saving objects
  • Using the “__sleep()” and “__wakeup()” magic functions
  • Creating persisting 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


    Using the Sleep and Wakeup Functions to Serialize Objects in PHP - Using the “__sleep()” and “__wakeup()” magic functions
    ( Page 3 of 4 )

    For those of you new to serializing objects in PHP, let me emphasize an important feature that can be used for different purposes: if you use the “serialize()” function on a specific object, the PHP interpreter will check whether there is a method called “__sleep()” and run its corresponding code prior to any serialization, assuming that this method has been defined.

    In a similar way, if the “unserialize()” function is applied to an object, the PHP parser will look for a method named “__wakeup()” and try to execute any code wrapped inside of it, before proceeding to unserialize the object in question.

    Since these functions are called transparently by the interpreter, it’s possible to create classes that take advantage of this automated process, in order to perform some useful tasks.

    To properly understand the concepts I deployed before, take a look at the following sample class, which displays a simple message each time the “__sleep()” and “__wakeup()” functions are called respectively:

    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 unserialized object from file
        function open(){
            if(!$obj=unserialize(file_get_contents($this-
    >objectFile))){
                trigger_error('Error fetching object from
    file',E_USER_ERROR);
            }
            return $obj;
        }
        // define '__sleep()' method
        function __sleep(){
            echo 'This method was called prior to serializing the
    object!<br />';
            return array_keys(get_object_vars($this));       

        }
        // define '__wakeup()' method
        function __wakeup(){
            echo 'This method was called after unserializing the
    object!<br />';
        }
    }

    In this case, I redefined the previous “ObjectSaver” class, and added to its signature the corresponding “__sleep()” and “__wakeup()” methods, so that it will display a basic message whenever they’re called up.

    After defining the modified “ObjectSaver” class, a basic -- yet illustrative -- demonstration of how these magic methods are called by the PHP interpreter is listed below:

    // show the functionality of __sleep() and __wakeup() methods
    $objSaver=&new ObjectSaver();
    $newObj=$objSaver->open();

    If you run the above script, you’ll get the following output:

    This method was called prior to serializing the object!
    This method was called after unserializing the object!

    As you can see, the example above shows that each time the “save()” and “open()” methods are called -- remember that these methods internally use the respective “serialize()/unserilalize() PHP functions –- the “__sleep()” and “__wakeup()” methods are also invoked, in this way displaying the messages shown above.

    Even though the previous example may seem rather rudimentary, it serves to demonstrate how these magic methods are called in a transparent way by the PHP interpreter. However, this recently-acquired knowledge about how these methods work can be used for performing more useful tasks than displaying basic messages.

    Keeping in mind the ability that PHP offers to call internally the mentioned methods, in the next section I’ll show you how to create objects that persist across several page requests without using any session mechanism. Go ahead and keep reading.



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

       

    PHP ARTICLES

    - 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
    - Method Chaining: Adding More Methods to the ...
    - Method Chaining in PHP 5
    - The Role of Interfaces in Applying the Depen...
    - Dependency Injection: Using a Setter Method ...
    - Using a Model Class with the Dependency Inje...
    - Injecting Objects Using Setter Methods with ...
    - Injecting Objects by Constructor with the De...
    - The Dependency Injection Design Pattern in P...
    - Performing Inferential Statistical Analysis ...
    - Performing Descriptive Statistical Analysis ...





    © 2003-2009 by Developer Shed. All rights reserved. DS Cluster 1 Hosted by Hostway
    Stay green...Green IT