As I expressed at the beginning of this article, one typical situation where dependency injection is used at its most efficient is when it comes to building applications that need to work with multiple database systems. To demonstrate this concept as clearly as possible, I’m going to start developing a PHP 5 program that will be capable of using both MySQL and SQLite to perform CRUD operations against a selected database. So, the first step that must be taken is defining a simple interface that will declare at an abstract level the methods that will be implemented by the respective database drivers. Now that I have explained that, please examine the definition of the following interface, which not surprisingly is called “DbHandler.” Here it is: // define 'DbHandler' interface
interface DbHandler { public function __construct($host, $user, $password, $database);
public function query($query);
public function fetch();
public function count(); } Were you expecting to see longer code? Sorry to disappoint you if you were, but I’d like to keep the structure of the above “DbHandler” interface pretty simple and uncluttered (after all, that’s the idea behind defining an interface, right?). As you can see, it declares four public methods that will come in handy for connecting to the specified database and running queries, as well as for fetching and counting rows in result sets. So far, there’s nothing unusual about the way that this interface has been defined. So, it’s time to start out building the first database driver class. This clase will be responsible for implementing the methods declared by the interface to work with MySQL. The definition of this class will be shown in the last section of this tutorial. Therefore, go ahead and read that segment.
blog comments powered by Disqus |
|
|
|
|
|
|
|