True to form, providing the previous “User” class with the capacity for saving its instances to different session variables is only a matter of tweaking the definition of its “factory() method and its destructor. Period. You don’t believe that this process can be that simple? Well, to prove this, below I listed the enhanced version of this class, which now defines its factory method in a slightly different way. Here it is: class User { private $data = array(); private static $key = 'user';
// constructor (not implemented) public function __construct(){}
// factory method public static function factory($key = '') { session_start(); if ($key != '') { self::$key = $key; } if(isset($_SESSION[self::$key]) === TRUE) { return unserialize($_SESSION[self::$key]); } return new User(); }
// set undeclared property public function __set($property, $value) { $this->data[$property] = $value; }
// get undeclared property public function __get($property) { if (isset($this->data[$property]) === TRUE) { return $this->data[$property]; } }
// save object to session variable public function __destruct() { $_SESSION[self::$key] = serialize($this); } } As I explained before, now the “factory()” method of the above “User” class accepts a $key input argument, which is used internally to create the session variable responsible for storing class instances. On the other hand, the implementation of the destructor is subtly different too, which is a natural consequence, since it has to reflect the change introduced into the factory method. Having provided the persistent “User” class with the ability to save its eventual instances to different session variables, it’s time to give it a try. In the final section of this tutorial I’m going to create another script, which will demonstrate the improved functionality of the aforementioned class. To see how this last code sample will be developed, click on the link below and read the next few lines.
blog comments powered by Disqus |
|
|
|
|
|
|
|