PHP
  Home arrow PHP arrow Page 3 - 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 - Combining objects and sessions: defining a session handling class
    ( Page 3 of 5 )

    In order to restructure the example I showed you in the previous section, I’ll simply define a session handling class, in such a way that all the tasks for registering, retrieving and deregistering objects will be handled from inside this class. Here is the signature of the “SessionHandler” class:

    class SessionHandler{
        function SessionHandler(){
            session_start();
        }
        // register object as session data
        function registerObject($obj,$objName='defaultObject'){
            if(!is_object($obj)){
                trigger_error($obj.' must be an
    object!',E_USER_ERROR);
            }
            if($objName==''){
                trigger_error('Invalid object name.',E_USER_ERROR);
            }
            $_SESSION[$objName]=$obj;
        }
        // deregister object from session data
        function unregisterObject($objName='defaultObject'){
            if(!$_SESSION[$objName]){
                trigger_error('Invalid object name.',E_USER_ERROR);
            }
            unset($_SESSION[$objName]);
        }
        // retrieve session object
        function getObject($objName='defaultObject'){
            if(!$_SESSION[$objName]){
                trigger_error('Invalid object name.',E_USER_ERROR);
            }
            return $_SESSION[$objName];
        }
    }

    As you can see, the session handling class listed above exposes a few simple methods, handy for registering objects in session variables, as well as for fetching and deregistering them. Based on the functionality provided by this brand new class, the example shown in the previous section can be rewritten as follows:

    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;
        }
    }

    // use 'SessionHandler' class to register and deregister objects
    $dataSaver=&new DataSaver('This object will be serialized and
    saved as session data.');
    // save string to file
    $dataSaver->save();
    // instantiate 'SessionHandler' object
    $sessHand=&new SessionHandler();
    // register session object
    $sessHand->registerObject($dataSaver,'datasaver');
    // deregister object
    $sessHand->unregisterObject('datasaver');
    // retrieve object after deregistering it (triggers a fatal
    error)
    $sessHand->getObject('datasaver');

    In this example, I registered a “$dataSaver” object on a session variable by using the “registerObject()” method that belongs to the “SessionHandler” class. Similarly, the referenced object can be retrieved or deregistered in turn, as shown at the end of the script.

    If you’re planning to use your registered objects across different pages during a particular session (as is usually done), again you must include, within all the files, the definition of all the classes that correspond to the objects that will be used.

    With reference to the previous example, say you want to restore and use a “DataSaver” object in a different page. This document should be coded like this:

    // 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;
        }
    }
    // define 'SessionHandler' class
    class SessionHandler{
        function SessionHandler(){
            session_start();
        }
        // register objects as session data
        function registerObject($obj,$objName='defaultObject'){
            if(!is_object($obj)){
                trigger_error($obj.' must be an
    object!',E_USER_ERROR);
            }
            if($objName==''){
                trigger_error('Invalid object name.',E_USER_ERROR);
            }
            $_SESSION[$objName]=$obj;
        }
        // deregister object from session data
        function unregisterObject($objName='defaultObject'){
            if(!$_SESSION[$objName]){
                trigger_error('Invalid object name.',E_USER_ERROR);
            }
            unset($_SESSION[$objName]);
        }
        // retrieve session object
        function getObject($objName='defaultObject'){
            if(!$_SESSION[$objName]){
                trigger_error('Invalid object name.',E_USER_ERROR);
            }
            return $_SESSION[$objName];
        }
    }
    // instantiate 'SessionHandler' object
    $sessHand=&new SessionHandler();
    // retrieve registered session object
    $dataSaver=$sessHand->getObject('datasaver');
    // call 'fetch()' method
    echo $dataSaver->fetch();

    In this specific example, I explicitly included the definition of all the classes that will be used at a later time, but obviously this should be done by using a “require_once()” statement, in order to simplify the script’s source code. Also, notice how the “$dataSaver” object is properly retrieved via the “getObject()” method that belongs to the “SessionHandler” class. Simple and instructive, right?

    At this stage, I think you’ve already grasped the basics of working with objects and sessions, which is an important part of object serialization, since this process is performed internally by the PHP interpreter. From this point onward, you can develop full-featured applications that will smartly combine your objects and sessions.

    Finally, the conclusion of this article will rest on setting up a practical example that will demonstrate how to store serialized objects in MySQL tables, instead of using conventional BLOBs.

    The last section of the article explains how to achieve this, therefore click on the link below to learn more on this topic.



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