In order to demonstrate how the use of some static properties can actually improve the behavior of a given class, in the following lines I'm going to start building the MySQL driver mentioned in the introduction. In this particular case, it will act like a simple wrapper for the built-in MySQLi PHP 5 class. Having explained my goal here, the initial definition of the wrapper will be as follows: class MySQLiWrapper extends MySQLi {
private $_config = array();
public 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); } } Well, that's no much to begin with, but it's better than nothing. As seen above, the previous "MySQLiWrapper" behaves exactly like a wrapper for the native MySQLi class that comes bundled with PHP 5. At this point, the class implements only two methods, its constructor and the public "connect()." The first one accepts an array of input parameters required for connecting to MySQL and selecting a specified database, and the last one performs the actual connection process. So far, nothing interesting is happening with this class, as there's no single sign that shows the use of a static property in it. However, since it'd be highly desirable to deal with only one instance of this driver, it'd be useful to turn it quickly into a Singleton class. We can do this by declaring a static property that controls the proper instantiation of the driver. Therefore, in the section to come I'm going to enhance the definition of the previous "MySQLiWrapper" class by adding to it the aforementioned static property, along with a whole new method that will manipulate this variable in a clever way. To learn more about this enhancement, click on the link below and read the following segment.
blog comments powered by Disqus |
|
|
|
|
|
|
|