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.
blog comments powered by Disqus |
|
|
|
|
|
|
|