If you found it easy to understand how the previous persistent class worked, then you’ll see that building one that stores its instances in a text file is an even simpler process. To demonstrate the veracity of my claim, I rebuilt the “User” class, which now will be capable of persisting through different HTTP requests, thanks to its ability for saving its spawned objects to a predefined file called “data.txt.” The new definition of this class is shown below, so take a look at it: class User { private $data = array(); private $file = 'data.txt';
// constructor public function __construct() { list($this->data['name'], $this->data['email']) = explode('|', file_get_contents($this->file)); }
// set undeclared property public function __set($property, $value) { if ($property !== 'name' and $property !== 'email') { return; } $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() { file_put_contents($this->file, $this->name . '|' . $this->email); } } Undeniably, the signature of the above “User” class looks at first sight quite similar to the one shown in the previous segment, with some important differences worth spotting. In this specific case, the class implements its constructor and destructor methods to seamlessly support the creation, loading and storage of its properties to a text file. Besides, the magic “__set()” and “__get()” methods have been slightly modified to accept creating only a couple of “name” and “email” properties. It's possible, of course, to code these to be a bit more permissive with reference to the properties that can be created. Having explained how the brand new “User” class does its thing, it’s time to give it a try and see if it’s really capable of persisting through several web pages, right? Below I coded a script that first spawns a user object, and then assigns some values to its properties; finally, it saves them to the specified “data.txt” file. Here’s the script that does all that: // example on using a persistent object with a text file $user = new User(); $user->name = 'Alejandro'; $user->email = 'alejandro@mydomain.com'; // __destruct() saves automatically the object to the target file Definitely, the “User” class does decent work saving the state of its instance to a text file, as you can clearly see from the above code fragment. However, this is only half of the process; it’s also necessary to see how the properties of that particular instance can be retrieved on a different web page. Showing how to perform that task will be the conclusion of this tutorial. So, to learn the full details of this process, go ahead and read the last section.
blog comments powered by Disqus |
|
|
|
|
|
|
|