As I explained in the section that you just read, it’s extremely simple to invert the roles played by the classes that you saw before, thanks to the functionality given by dependency injection. In this particular case, I’m going to implement only a specific flavor of it, where the dependency of a class is passed in through a constructor. To show you the benefits of dependency injection, the only thing that I’m going to do next is modify the constructor of the persistent “User” class, which now will look as follows: 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 implementing the dependency injection pattern was a simple process? Well, the tweaked definition of the “User” class proves that without a doubt. As you can see, now the class’s constructor is no longer responsible for creating an instance of the database handler; it simply takes it smoothly as an incoming argument. It’s probable that you’ve already coded your classes that way, even without knowing that you were using the benefits of dependency injection. Now you know it, and you should feel proud of it. Returning to the definition of the “User” class, since its dependency is passed to its internals via the constructor, the process, not surprisingly, is known as “dependency injection by constructor.” But there are other ways to achieve the same result. However, for the moment I’m going to explore only this introductory approach. So far, so good. At this point, you’ve hopefully grasped the underlying logic of the dependency injection pattern, meaning that it’s time to see how the proper implementation of this pattern can improve the way that persistent objects are created. Thus, in the last segment of this tutorial I’m going to set up a final example for you. It will show how the modified version of the “User” class will now behave much more efficiently when it comes to handling its dependency. To see how this example will be developed, click on the link below and keep reading.
blog comments powered by Disqus |
|
|
|
|
|
|
|