In the previous section, I implemented the first two methods of a basic MySQL driver, whose underlying logic has been hopefully easy for you to grasp. At this point, the class doesn't explicitly use any static property to improve its behavior. This is about to change. Since in most cases a database handler object will be shared by other objects within the context of an application, the earlier driver is an excellent candidate for turning into a Singleton class. Of course, one can use several approaches to achieve this; in this example, I'm going to use a static property to assure that only one instance of the driver is always returned to client code. Having said that, look at the enhanced version of the previous "MySQLiWrapper" class. This time, it implements a new static method called "getInstance()" that returns a Singleton instance of it by controlling the aforementioned static property: class MySQLiWrapper extends MySQLi {
private static $_instance = NULL; private $_config = array();
// return Singleton instance of MySQL class public static function getInstance(array $config = array()) { if (self::$_instance === NULL) { self::$_instance = new self($config); } return self::$_instance; }
// private constructor private function __construct(array $config) { if (count($config) < 4) { throw new Exception('Invalid number of connection parameters'); } $this->_config = $config;
}
// prevent cloning class instance private function __clone(){}
// establish a connection to MySQL public function connect() { list($host, $user, $password, $database) = $this->_config; parent::__construct($host, $user, $password, $database); if ($this->connect_error) { throw new Exception('Error connecting to MySQL : ' . $this->connect_errno . ' ' . $this->connect_error); } unset($host, $password, $database); } } Admittedly, after adding the brand new "getInstance()" static method to the MySQL driver, things are starting to look slightly more interesting. This method uses a static $_instance property as a flag which ensures that only a single instance of the driver can be created at runtime. Even though the combination of a static property and a static factory method isn't the only way to develop a Singleton class, the above code fragment does show in a nutshell how useful this type of property can be for implementing this popular design pattern. All in all, now that this sample MySQL driver has been turned into a Singleton class, it's time to make it a bit more functional; right now it's only capable of connecting to the server and selecting a specified database. That's not too much, really. Thus, in the last section I'm going to give the driver the ability to perform SQL queries, finding insertion IDs and so forth by implementing a few additional methods. However, to learn more about how these will be defined, you'll have to click on the link below and keep reading.
blog comments powered by Disqus |
|
|
|
|
|
|
|