PHP
  Home arrow PHP arrow Page 2 - Working with MySQL and Sessions 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

Working with MySQL and Sessions to Serialize Objects in PHP
By: Alejandro Gervasio
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: starstarstarstarstar / 13
    2006-06-20


    Table of Contents:
  • Working with MySQL and Sessions to Serialize Objects in PHP
  • The basics of automated object serialization: using objects and sessions
  • Combining objects and sessions: defining a session handling class
  • Another implementation of object serialization: saving objects to MySQL tables
  • The complete list of classes for the example

  • 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


    Working with MySQL and Sessions to Serialize Objects in PHP - The basics of automated object serialization: using objects and sessions
    ( Page 2 of 5 )

    Registering objects as session data is really a straightforward process, since it doesn’t differ too much from registering other data types. However, there’s a couple of things that must be taken into account when using objects and sessions.

    First off, when an object is registered in a session, it will be automatically serialized during the registration process, and in turn unserialized if the object is eventually stored in a new variable. As you can see, the complete serialize/unserialize sequence is entirely handled by the PHP interpreter, so in theory you shouldn’t worry about how your objects are handled behind the scenes.

    Nevertheless, the second point to consider when working with objects and sessions is that all the pages where an object will be handled as session data (including registration, manipulation, deregistration, and so on)  must include the definition of the class (or classes) from which the object in question is spawned.

    To clarify the concepts that I deployed before, I start with a simple example – an object that will be registered during a regular session. Here is the corresponding code:

    // define sample 'DataSaver' class
    class DataSaver{
        var $data;
        var $dataFile;
        function DataSaver($data,$dataFile='defaultDir/data.txt'){
            if(!is_string($data)){
                trigger_error('Invalid data type',E_USER_ERROR);
            }
            $this->data=$data;
            $this->dataFile=$dataFile;
        }
        // save data to file
        function save(){
            if(!$fp=fopen($this->dataFile,'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->dataFile)){
                trigger_error('Error opening data
    file',E_USER_ERROR);
            }
            return $contents;
        }
    }
    // instantiate 'DataSaver' object
    $dataSaver=&new DataSaver('This object will be serialized and
    saved as session data.');
    // register 'DataSaver' objects as session data
    session_start();
    $_SESSION['object']= $dataSaver;

    In the above example, you can see that I included the definition of the sample “DataSaver” class before instantiating an object from it, and naturally prior to registering this object in a session variable.

    Now, I’ll suppose that a “$dataSaver” object needs to be used on a different page, after being registered during the prior session. Considering this situation, this sample page should be coded as follows:

    // define sample 'DataSaver' class
    class DataSaver{
        var $data;
        var $dataFile;
        function DataSaver($data,$dataFile='defaultDir/data.txt'){
            if(!is_string($data)){
                trigger_error('Invalid data type',E_USER_ERROR);
            }
            $this->data=$data;
            $this->dataFile=$dataFile;
        }
        // save data to file
        function save(){
            if(!$fp=fopen($this->dataFile,'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->dataFile)){
                trigger_error('Error opening data
    file',E_USER_ERROR);
            }
            return $contents;
        }
    }
    session_start();
    $dataSaver=$_SESSION['object'];
    echo $dataSaver->fetch();

    As shown above, I included the complete definition of the “DataSaver” class before any attempt to resume the previous session and restore the respective object. Once this has been successfully done, the “$dataSaver” object is restored and its “fetch()” method is called appropriately. The output of the previous script is the following:

    This object will be serialized and saved as session data.

    As you can see, if you’re careful enough and include the corresponding class definitions of all the objects you’ll be working with, you shouldn’t have any problems combining objects and sessions.

    All right, in the previous example you learned how to register objects in session variables, but the entire registration process was handled procedurally. Therefore, in the next section I’ll restructure the code sample you saw before, and create a simple session handling class. It will have the ability to register, fetch and deregister objects. Please go ahead and read the next few lines.



     
     
    >>> 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 2 Hosted by Hostway
    Stay green...Green IT