Home arrow PHP arrow Page 3 - Working with MySQL and Sessions to Serialize Objects in PHP

Combining objects and sessions: defining a session handling class - PHP

If you're interested in learning how to combine objects, sessions and MySQL, this is the article that you’ve been waiting for. It's the final part of the series “Serializing objects in PHP.” In three parts, this series goes through the fundamentals of serializing objects in PHP applications, and explores some advanced topics with regard to this subject, including the use of the magic “__sleep()” and “__wakeup()” functions, and the manipulation of serialized objects inside of MySQL tables.

TABLE OF CONTENTS:
  1. Working with MySQL and Sessions to Serialize Objects in PHP
  2. The basics of automated object serialization: using objects and sessions
  3. Combining objects and sessions: defining a session handling class
  4. Another implementation of object serialization: saving objects to MySQL tables
  5. The complete list of classes for the example
By: Alejandro Gervasio
Rating: starstarstarstarstar / 16
June 20, 2006

print this article
SEARCH DEV SHED

TOOLS YOU CAN USE

advertisement

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
 

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: