As you may have guessed, applying the dependency injection pattern through a setter method with the user model class that you saw before is only a matter of coding the method in question, so it can take in an instance of the corresponding MySQL handler. It’s that easy, really. Nevertheless, to help you understand this process more quickly, below I listed the modified version of the “UserModel” class, which now includes this whole new method. Study the following code sample, please: class UserModel { private $db = NULL;
// constructor (not implemented) public function __construct(){}
// setter for database handler public function setDatabaseHandler(MySQL $db) { $this->db = $db; }
// get all users public function getAll() { return $this->db->query("SELECT * FROM users"); }
// get a single user public function get($id = 1) { return $this->db->query("SELECT * FROM users WHERE id = '$id'"); }
// create/update user public function save($data, $id = NULL) { if (is_array($data) && !empty($data)) { if ($id === NULL) { $data = array_values($data); $fields = ''' . implode("','", $data) . '''; $this->db->query("INSERT INTO users (id, fname, lname, email) VALUES (NULL, $fields)"); } else { $fields = ''; foreach ($data as $field => $value) { $fields .= $field . '='' . $value . '','; } $fields = substr($fields, 0, -1); $this->db->query("UPDATE users SET $fields WHERE id=$id"); } } }
// delete user public function delete($id = NULL) { if ($id !== NULL) { $this->db->query("DELETE FROM users WHERE id=$id"); } } } See how simple it is to implement dependency injection via a setter method within the above model class? I bet you do! In this particular case, this brand new method, called “setDatabaseHandler(),” plays the same role as the older constructor -- that is, it accepts an instance of the “MySQL” class, which is finally stored as a property for further use. At first sight, it seems that this approach requires you to write more code than when using a constructor, which is undeniably true. However, there are times when a class will need to take in multiple dependencies to work properly. In a case like this, a setter method might be the most appropriate option to use, but in the end, which approach to implement will depend on your own personal preferences. Having already modified the definition of the previous “UserModel” class to make it accept its dependency via a setter method, the next step we must take is creating a script that shows this approach in action. Therefore, in the final section of this tutorial I’m going to code that script for you, which hopefully will give you a more solid understanding of how to implement dependency injection by using a slightly different approach. Now, go ahead and read the following segment, please. We’re almost done!
blog comments powered by Disqus |
|
|
|
|
|
|
|