Login   Register  
PHP Classes
elePHPant
Icontem

File: example.txt

Recommend this page to a friend!
Stumble It! Stumble It! Bookmark in del.icio.us Bookmark in del.icio.us
  Classes of Vit Ek  >  Object Session Saver  >  example.txt  >  Download  
File: example.txt
Role: Documentation
Content type: text/plain
Description: A further explanation of the example.php
Class: Object Session Saver
Save and restore objects in session variables
Author: By
Last change:
Date: 2007-03-08 09:29
Size: 1,826 bytes
 

Contents

Class file image Download
SessionSaver class

For usage see example.php

The purpose of this class and interface is to have way 
how to easily keep object's data over consecutive page loads.
For achieving this, we store the data in PHP SESSION.

First, we need to define objects which we plan to save to session
and add them with method addObjects(array $objectsForSaving)
of the SessionSaver class.
<?php
	$objectsForSaving = array("ExampleClass");
	SessionSaver::addObjects($objectsForSaving);
?>


Then we can start the session with something like this:
<?php
	if (empty($_SESSION)) {
		session_start();
	}
?>

After we started the session, we can call
SessionSaver's method restoreObjects(), it needs to be called
before any execution of the code which would use any 
of the classes which we previously added for saving
<?php
	SessionSaver::restoreObjects();
?>

Easy like that, now we have all the object's state restored
as if no pageload occured.
This method makes following things:
it calls implemented interface method setObjectState($objectState)
on each class in array previously added with SessionSaver::addObjects() method.
$objectState is data which returns second interface method getObjectState()


On the end of the script we need to call 
<?php
	SessionSaver::saveObjects();
?>

This method makes following things:
for each class in array previously added with addObjects() method
it calls implemented interface method getObjectState() to obtain
object's state and saves this state to session variable.


In case you would need to forget object's state, use methods
SessionSaver::removeObject(string $className) for one object at a time
SessionSaver::removeAllObjects() for forgeting state of all objects

This paradigm is well suitable for managing singletons but not only them.