Spawning a persistent object from the User class - PHP
If you’re a PHP developer who wants to learn how to create objects that can maintain their state through different HTTP requests, either by using cookies, plain text files or MySQL database tables, then don’t look any further because you’ve come to the right place. Welcome to the last part of a six-part series on building persistent objects in PHP 5. This tutorial series introduces the key concepts that surround the creation of persistent objects, and complements the corresponding theory with copious code samples.
In the previous segment, I explained briefly how the "MySQL" and "User" classes do their respective businesses, but always theoretically. Now, it's time to see how they can be used for creating an object capable of maintaining the values assigned to its properties through different HTTP requests.
Below I coded a simple script that first spawns an object from the originating "User" class, along with a couple of properties, and then saves those properties to the sample "users" MySQL table, thanks to the functionality provided by the corresponding MySQL abstraction class.
The source code of the script is as follows:
// example on using a persistent object
// connect to MySQL
$db = new MySQL('host', 'user', 'password', 'database');
$user = new User($db);
// create user properties and assign values to them
$user->name = 'Alejandro';
$user->email = 'alejandro@mydomain.com';
// __destruct() saves automatically object's properties to the database
See how simple it is to create a database-driven persistent object in PHP 5? The above code sample should answer this question for itself. As I explained earlier, once an instance of the "MySQL" class has been injected into the constructor of "User," the "name" and "email" properties created dynamically are stored automatically on the "users" MySQL table, thanks to the clever implementation of the destructor.
Of course, it's valid to point out here that all of these operations could be performed using a group of regular methods, instead of the magic ones available in PHP 5. For instance, instead of implementing a destructor to save the properties of an object, a regular "save()" method could be used to produce the same result.
However, since my purpose here was demonstrating how to create a persistent object with a minimal amount of code, I decided to use the magic methods that you saw before.
Having clarified that point, and now that the properties of the previous $user object have been stored in the corresponding MySQL table, the only step that remains is to show you how the properties in question can be restored on a different web page.
This process will be discussed in detail in the last section of this tutorial. Thus, to get there simply click on the link below and keep reading.