As I said in the segment that you just read, the best way to understand how an instance of the “User” class defined earlier can be turned into a persistent object is by means of a simple example. Below I included the complete source code of the class, complemented by a short script that shows how to create an object that persists across multiple HTTP requests, naturally assuming that session support has been enabled on the testing web server. Here’s the corresponding code sample, so take your time to examine it closely: 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]; } }
// save object to session variable public function __destruct() { $_SESSION['user'] = serialize($this);
} }
// example on using a persistent object $user = User::factory(); $user->fname = 'Alejandro'; $user->lname = 'Gervasio'; $user->email = 'alejandro@mydomain.com'; There you have it. Believe it or not, creating a basic persistent object with PHP 5 is really a simple process, as demonstrated by the above code fragment. In this case, the “$user” object, which happens by mere coincidence to represent myself, has been assigned some properties, including my first and last names, and my (fictional) email address as well. Nonetheless, there’s something else going on under the surface of the previous script. Once it finishes running, the destructor method is called, which saves the object to the predefined session variable. In doing so, it’s possible to restore it on a different web page and keep handling it as one would do with regular session data. Finally, feel free to edit all of the code samples included in this tutorial, which hopefully will arm you with a better grounding in building persistent objects in PHP 5. Final thoughts That’s all for now. In this introductory chapter of the series, you learned the basics of creating persistent objects with PHP 5, which in this introduction to the subject used native sessions as the underlying persistent storage mechanism. Also, it’s valid to point out that the class that I created in this article isn’t very flexible in its current state, because it permits you to use only a predefined session variable to store an instance of it. To overcome this issue, in the next tutorial I’m going to tweak its definition so that it’ll be able to use any user-supplied session variable. Don’t miss the next part!
blog comments powered by Disqus |
|
|
|
|
|
|
|