Having already defined an interface that declares some generic methods not tied to a specified database system, I’m going to build the driver class that will interact specifically with MySQL. Of course, this class will give a concrete implementation to all of the methods defined by the interface, and its signature is as follows:
class MySQL implements DbHandler { private $result = NULL; private $link = NULL;
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)) { 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; } // count rows in result set public function count() { if ($this->result !== NULL) { if (0 === ($rows = mysqli_num_rows($this->result))) { return 'No rows in result set'; } return $rows; } } } As seen above, this new “MySQL” class is nothing but a shortened version of the example shown in previous chapters of the series, except for one important difference. In this case, this class is an implementer of the “DbHandler” interface. What does this mean in practical terms? Well, in other words, it can be said that any instance created from the “MySQL” class will eventually be a polymorph object. But, actually I’m getting ahead of myself, since this concept will be much better understood when I define the driver for SQLite, over the course of the upcoming article. In the meantime, it’s time to recapitulate the things that have been accomplished so far. First, I defined an interface whose methods were implemented by a MySQL database driver. That is good, but it’s possible that you’re wondering where dependency injection comes into play, right? However, as you may know, a long way always takes many small steps, so bear with me for the moment. In the next tutorial I’m going to take the next step by defining the driver class that will be responsible for interacting with SQLite, which not surprisingly will be another implementer of the “DbHandler” interface. Final thoughts That’s all for the moment. In this sixth episode of the series, I began building a PHP 5-based application that will have the ability to work seamlessly with MySQL and SQLite. In its current state, this application is composed only of a simple interface and a MySQL driver; therefore, it’s necessary to build the class that will interact specifically with SQLite. That’s exactly what you’ll learn to do in the next article, so you don’t have any excuses to miss it!
blog comments powered by Disqus |
|
|
|
|
|
|
|