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

The basics of automated object serialization: using objects and sessions - 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

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
 

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: