In order to explain how to create persistent objects in PHP 5, I’m going to begin building a simple class. It will use PHP’s native session mechanism to save a particular state of an object that stores some trivial data on a fictional user. You'll understand the way this class will work much better if you see its initial definition, so below I included its partial source code. Pay close attention to it: class User { private $data = array();
// constructor (not implemented) public function __construct(){}
// factory method public static function factory() { session_start(); if(isset($_SESSION['user']) === TRUE) { return unserialize($_SESSION['user']); } 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]; } } } As I explained a few moments ago, all that the above “User” class does is store an instance of itself in a simple session variable, in this particular case referenced as $_SESSION[‘user’]. This specific instance will first be created via a static factory method, which will load this object either from the session variable, or as an empty entity via a regular “new” construct. Also, for the sake of making the class’s code a bit more compact I decided to implement the “__set()” and “__get()” magic PHP methods to assign and retrieve properties dynamically through the $data internal array. Naturally, the same process can be performed by declaring those properties within the class’s body. Well, now that I have outlined how the previous “User” class functions, hopefully you’ll have a better idea of how to create objects that can save their state to a session variable, thus persisting across several HTTP requests. But, wait a minute! The class in question actually doesn’t implement a method that saves an instance of itself. Where is that method, then? To be honest, it needs to be defined first, and then properly implemented. However, this process will be discussed in detail in the section to come. So, to learn more about it, click on the link shown below and read the following segment.
blog comments powered by Disqus |
|
|
|
|
|
|
|