Using a Model Class with the Dependency Injection Design Pattern

Welcome to the fourth part of a series on applying the dependency injection design pattern in PHP 5. Through a strong hands-on approach, this series teaches you several methodologies that you can use for taking advantage of the functionality given by this simple yet powerful design pattern. It shows you how to build classes that follow the schema imposed by the Inversion of Control software design principle.

And now that you’ve been introduced to the goal of this series, it’s time to review the topics that were covered in the last article. In that tutorial I explained how to apply the dependency injection pattern with a couple of sample classes.

In this concrete example, the first of these classes was a basic MySQL database handler, while the latter was a persistent class, which required of the functionality of the first to work properly. Asides from outlining how the classes interacted with each other, the most relevant detail is the fact that the persistent class implemented a simple setter method for inputting an instance of the database handler into its internals.

This kind of relationship between classes, where a setter method is employed to inject an object into the inside of another one, is commonly know as “dependency injection by setter method.” It’s another way of implementing the dependency injection pattern.

However, this pattern can be used in multiple scenarios and environments, even though so far it’s been overlooked by some developers. In reality, the pattern plays a relevant role in applications that use the Model-View-Controller paradigm, which as you know is extremely popular these days.

Therefore, in the next few lines I’m going to show you how to apply dependency injection within a model class that will handle a MySQL table containing records on some fictional users.

Want to see how to combine the functionality of the MVC and the dependency injection patterns in one single PHP 5 program? Then begin reading right now!

{mospagebreak title=Defining a MySQL abstraction class}

Since my plan here consists of showing how to implement the dependency injection pattern within the context of a MySQL-driven application that follows the MVC schema, the first step is building a class that permits you to interact easily with the MySQL server.

Fortunately for you and me, this class was already built in previous articles of this series. So I’m simply going to list its complete source code, which looks like this:

class MySQL

{

private $result = NULL;

private $link = NULL;

private static $instance = NULL;

 

// returns a singleton instance of MySQL class (chainable)

public static function factory($host, $user, $password, $database)

{

if (self::$instance === NULL)

{

self::$instance = new MySQL($host, $user, $password, $database);

}

return self::$instance;

}

// connect to MySQL

public function __construct($host, $user, $password, $database)

{

if (FALSE === ($this->link = mysqli_connect($host, $user, $password, $database)))

{

throw new Exception(‘Error : ‘ . mysqli_connect_error());

}

}

 

// perform query

public function query($query)

{

if (is_string($query) AND empty($query) === FALSE)

{

if (FALSE === ($this->result = mysqli_query($this->link, $query)))

{

throw new Exception(‘Error performing query ‘ . $query . ‘ Error message :’ .mysqli_error($this->link));

}

}

}

 

// fetch row from result set

public function fetch()

{

if (FALSE === ($row = mysqli_fetch_assoc($this->result)))

{

mysqli_free_result($this->result);

return FALSE;

}

return $row;

}

 

// get insertion ID

public function getInsertID()

{

return mysqli_insert_id($this->link);

}

// count rows in result set

public function countRows()

{

if ($this->result !== NULL)

{

return mysqli_num_rows($this->result);

}

}

// implement destructor to close the database connection

function __destruct()

{

mysqli_close($this->link);

}

}

If you’ve read all of the articles that preceded this one, then the signature of the above “MySQL” class should be familiar to you. It’s been used previously with other examples. This class performs a few basic tasks, such as running queries against a selected database and finding insertion IDs, as well as retrieving and counting rows in a data set.

So far, there’s nothing unexpected about the way that this MySQL abstraction class works, so it’s time to continue developing other building blocks of this sample application that will use both the MVC and the dependency injection patterns as its driving force.

In the section to come I’m going to build the class that stands behind the “M” letter of the MVC schema —  a simple model that will be responsible for handling some user-related records.

To learn the full details of how this model class will be developed, please click on the link that appears below and keep reading.

{mospagebreak title=Building a model class}

In the preceding segment, I showed the definition of the class that will allow you to access MySQL tables in a quite abstract way. So, the next thing we must do toward the development of the MVC-based application is build a model class that will use the MySQL handler for manipulating records related to some fictional users.

Below I included the source code of this brand new model class, which has been called, not surprisingly, “UserModel.” Study its definition, please:

class UserModel

{

private $db = NULL;

 

// constructor

public function __construct(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");

}

}

}

Well, I don’t wan to sound too verbose, but you’ll have to agree with me that the definition of the previous “UserModel” class has some interesting points that deserve a close analysis. First, as one would expect from a decent model, the class implements some simple methods that allow it to perform CRUD operations in a straightforward manner.

And last but not least, the model takes an instance of the MySQL handler, which is naturally used by the pertinent methods to execute the CRUD operations against a predefined “users” MySQL table.

This example is very illustrative because it shows how to create a model in a few simple steps, and demonstrates how the dependency injection pattern can be implemented with minor hassles within the MVC schema. What else can you ask for?

In reality you can ask for much more. It’s quite possible that at this moment you’re wondering how to use the two classes shown before for inserting, updating and deleting users without having to directly write any SQL query.

Is that what you’re asking for? In the section to come I’m going to code a simple script that will perform all of those operations in a very simple manner. Naturally, to learn how this script will be built, you’ll have to click on the link below and read the following lines.

{mospagebreak title=Performing CRUD operations with the user model class}

Without a doubt, the best way to understand how the sample classes shown before can be put to work together is by developing a small application that shows how to run CRUD operations against the fictional “users” MySQL table.

Provided that the corresponding definitions of these classes have been previously included either as a single file or as a set of separate dependencies, then inserting, updating and deleting users would be as simple as this:  

// create new instance of MySQL class

$db = new MySQL(‘host’, ‘user’, ‘password’, ‘database’);

// inject instance of MySQL in the model via its constructor

$userModel = new UserModel($db);

// add new user

$userModel->save(array(‘fname’ => ‘Alejandro’, ‘lname’ => ‘Gervasio’, ‘email’ => ‘alejandro@domain.com’));

// update existing user

$userModel->save(array(‘fname’ => ‘Mary’, ‘lname’ => ‘Wilson’, ‘email’ => ‘mary@domain.com’), 1);

// delete existing user

$userModel->delete(1);

From the previous script, it’s clear to see that the combined functionality of both the MVC and the dependency injection patterns can lead to coding programs that not only separate properly application logic from visual presentation, but in which their building classes are loosely coupled.

In this particular example, the database handler (or in other words, the dependency) is injected into the internals of the model via the constructor of the latter, but as you know it’s possible to achieve the same result with a setter method.

Finally, I suggest that you edit some of the code samples developed in this tutorial, which hopefully will equip yourself with a better understanding of how to apply the dependency injection pattern in PHP 5.

Final thoughts

In this fourth installment of the series, you learned how to merge the functionality of both the Model-View-Controller and the dependency injection patterns, to build a MySQL-driven application that perform CRUD operations on a “users” database table.

In this case, the dependency was passed to the model class via the constructor of the second one, but as I said before, it’s also feasible to implement a setter method to accomplish this task with similar results.

This approach will be discussed in depth in the next tutorial, so you don’t have any excuses to miss it!

[gp-comments width="770" linklove="off" ]
antalya escort bayan antalya escort bayan