myPHP

I would like to share my PHP ideas and thus use this place for displaying them.

persistent objects in PHP?

Within some applications it is necessary to store data of complete objects for later use. Unfortunately there is no buildin solution as far as I know. One simple way is to hand the storing and restoring over to the object itself. So I created a base class which is able to create itself either from the current session if available or completly new when no session has been started yet. This is a kind of a workaround but it is easy and working well.

Note: For get_called_class() a PHP version of minimum 5.3.0 is required.

Here is my persistent base class

/*
* This is my persistent php object base class
* -------------------------------------------
*
* how to use it:
* 1. derive a class via "extends" (see example)
* 2. call $obj = MyObject::createPersistent( 'abcd' );
* 3. use the $obj as you want it is now stored automatically!
* 4. don't belive it? try it!
*
*/
class SessionObject{

var $storageName;
var $className;

function __construct(){
}


// save this or derived objects on destruction
function __destruct(){
$this->store();
}

/*
* a call to this static function searches in the session
* for the desired object or alternatively creates a new object
* of this kind
*/
static function createPersistent( $objectID ){
$class = get_called_class();
$storageName = $class.'_ID_'.$objectID;


if (array_key_exists($storageName, $_SESSION)){
echo 'Restored '.$storageName.'';
return $_SESSION[$storageName];
} else {
echo 'create '.$class.' with ID '.$objectID.'';
$temp = new $class();
$temp->storageName=$storageName;
$temp->className=$class;
return $temp;
}
}

// internal store function
function store(){
$_SESSION[$this->storageName] = $this;
echo "Stored ".$this->storageName.'';
}


}

Now an persistent object could be as simple as this

 /*
* my demo object
*/
class MyObject extends SessionObject{

var $test;

function __construct(){
$this->test = 10;
}

}

and the creation call of the object is here

 // here is the magic : create the object
$obj = MyObject::createPersistent( 'abcd' );

Thats it! Now just use the object as usal. All members are beeing stored automatically in the base class.

Download the complete demo : SessionObjectDemo.php

 

based on a template by jimmy