As I expressed in the introduction, my goal in this tutorial will consist of demonstrating how to use a private constructor within a class that will abstract the access to MySQL. In simple terms, this sample class will implement a Singleton static method, which as you may guess, will permit it to spawn only one instance of the MySQL driver. Undoubtedly, a database abstraction class is really a good candidate for turning into a Singleton. Having said that, take a look at the following code fragment, which shows the partial definition of the class in question. Here it is: class MySQL { private $_result = NULL; private $_link = NULL; private $_config = array(); private static $_instance = NULL;
// 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(){} } As seen above, the “MySQL” abstraction class implements for the moment only two methods. The first one is the static “getInstance(),” which is responsible for returning to client code a Singleton instance of the class. On the other hand, the second one is the constructor that accepts an array of parameters required for connecting to the server and selecting a specified database. So far, the constructor has nothing particularly special, except for a tiny subtlety: it's been declared private. The reason for doing so is self-explanatory: by preventing the constructor from being called from the outside, the unique access point to a single instance of the class is the aforementioned “getInstance()” method. That was simple to grasp, right? In addition, to give the Singleton pattern a stricter implementation, the magic “__clone()” PHP 5 method has also been defined private, a process that avoids directly cloning instances of the class. Even though at this point the earlier MySQL driver is only composed of a few straightforward methods, it's handy for illustrating a typical case where a private constructor can be of great help concerning the application of a specific design pattern. Nonetheless, the driver in its current state isn’t very useful, meaning that it’s necessary to add more methods to it that extend its limited functionality. With that idea in mind, in the following section I’m going to code some additional methods. They will give the driver the ability to connect lazily to the server and run queries, fetch database rows and a few more useful tasks. To see how these brand new methods will be defined, click on the link below and read the section to come.
blog comments powered by Disqus |
|
|
|
|
|
|
|