To demonstrate how to build a persistent class that will store its properties in a MySQL table, I’m going to redefine the “User” class utilized in this article and in previous ones, which hopefully will make this development process much easier to understand for you. Having clarified that point, here’s the new definition of the aforementioned class, which now looks like this: // define 'User' class (stores object properties on a database table) class User { private $data = array(); private $id = 1; private $db = NULL;
// constructor public function __construct(MySQL $db, $id = NULL) { $this->db = $db; if ($id !== NULL) { $this->id = $id; } $this->db->query('SELECT * FROM users WHERE id=' . $this->id); $this->data = $this->db->fetch(); }
// 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 class properties to MySQL table public function __destruct() { $this->db->query("UPDATE users SET name = '$this->name', email = '$this->email' WHERE id = $this->id"); } } As I explained earlier, the skeleton of this “User” class remains nearly the same as its previous versions, except for its constructor and destructor methods, which are the ones that actually do the dirty work. The first method is responsible for retrieving the properties of the class from a specified MySQL table, while the second one is tasked with saving them back. In this specific example, I used the term “retrieving” on purpose because the constructor uses an injected instance of the MySQL class defined previously to retrieve the properties from a fictional “users” MySQL table according to the supplied ID. On the other hand, the destructor simply updates the corresponding table record with new data, in case the properties have been updated as well. Of course, the best way to understand how the above persistent class functions is by way of a concrete example, but this will be created in the last part of the series. Anyway, I guess that at this point you have a clear idea of how to spawn a persistent object by using the two classes defined before. So, if you feel this will be a no-brainer process, then go for it! Final thoughts In this penultimate part of the series, I went through the development of a persistent class that had the ability to save its properties to a MySQL table. Naturally, if you’re like me, it’s probable that you want to see an example that shows how to use this class. However, this example will be created in the final article, so now that you’ve been warned, you don’t have any excuses to miss it!
blog comments powered by Disqus |
|
|
|
|
|
|
|