PHP Page 3 - Injecting Objects Using Setter Methods with the Dependency Injection Design Pattern |
As I stated in the preceding section, it’s possible to implement the Dependency Injection pattern by means of a setter method, instead of using a constructor. This approach can be handy in those cases where a given class needs to take in multiple dependencies to work properly. However, to demonstrate the implementation of this specific approach I’m going to reuse the couple of sample classes shown previously, so you can spot the difference between injecting dependencies via a constructor and via a setter method. Now it’s necessary to modify the definition of the persistent “User” class and add to it the setter method. Here’s the modified version of this class: class User { private $data = array(); private $id = NULL; private $db = NULL;
// implements dependency injection via a setter method public function setDatabaseHandler(MySQL $db) { $this->db = $db; }
// initialize user object public function load($id = NULL) { 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"); } } }
As seen above, now the “User” class implements a brand new method called “setDatabaseHandler().” This method is responsible for taking from outside an instance of the database handler, and then saving this object as a class property. If you ever thought that applying the dependency injection pattern using a setter method was a difficult process, then feel glad to know that you were wrong! And now that you've surely grasped the logic that drives the above “User” class, it’s time to code an example that shows how to use it in conjunction with its dependency, that is, the corresponding MySQL database handler. So, with that goal in mind, in the next section of this tutorial I’m going to create that example for you, thus finishing this introduction to applying dependency injection through a setter method. Now, click on the link that appears below and read the following segment, please.
blog comments powered by Disqus |
|
|
|
|
|
|
|