In the earlier segment, I reintroduced the example created in the previous tutorial of this series, which showed how to construct a pair of persistent objects by using a basic MySQL abstraction class. As I explained in that section, though, the class that originates these persistent objects is charged with creating an instance of the database handler, which introduces a serious issue that goes to the detriment of building loosely decoupled classes. Luckily, this issue can be fixed with only minor headaches, simply by moving the factory method of the database handler out of the constructor of the “User” class. If this explanation sounds confusing to you, then pay close attention to the modified definition of this class, which now looks like this: class User { private $data = array(); private $id = NULL; 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 object to session variable public function __destruct() { if ($this->id === NULL) { $this->db->query("INSERT INTO users (id, name, email) VALUES (NULL, '$this->name', '$this->email')"); } else { $this->db->query("UPDATE users SET name = '$this->name', email = '$this->email' WHERE id = $this->id"); } } } Didn’t I tell you that the coupling issue could be solved easily? Well, if you look at the improved definition of the “User” class, then you’ll realize that I was right! As shown above, the factory method that originally created an instance of the database handler has been completely removed from the class’s constructor, thus delegating this task to its outer environment. Now the constructor simply accepts an instance of the database handler as a passive player, which is expected to be supplied from the outside, rather than from its inner context. This approach is commonly known as “dependency injection by constructor,” and its implementation is as simple as that. So far, so good. Having introduced that small change into the definition of the previous persistent user class, the next step is to set up an example that shows how this class and its corresponding database dependency can be put to work in tandem. Therefore, in the last section of this article I’m going to create that example for you. Now, simply click on the link below and keep reading.
blog comments powered by Disqus |
|
|
|
|
|
|
|