As I explained in the previous section, preventing the "MySQLiWrapper" class from attempting to connect to MySQL multiple times can be handled through the use of an additional static property. Basically, the idea is to utilize this variable as a flag that makes sure that the connection is made only once. However, the concrete implementation of this solution should be done within the "connect()" method of the class. This point is demonstrated by the code sample below. Take a look at it, please:
class MySQLiWrapper extends MySQLi {
private static $_instance = NULL; private static $_connected = FALSE; 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() { // if no previous connection exits, connect to MySQL if (self::$_connected === FALSE) { 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); } // connection is successful self::$_connected = TRUE; unset($host, $password, $database); } }
// perform query public function runQuery($query) { if (is_string($query) AND !empty($query)) { // lazy connect to MySQL $this->connect(); // run the specified query if ((!$this->real_query($query))) { throw new Exception('Error performing query ' . $query . ' - Error message : ' . $this->error); } return new MySQLi_ResultWrapper($this); } }
// get insertion ID public function getInsertID() { return $this->insert_id; }
// close database connection public function __destruct() { $this->close(); } } Now, the "MySQLiWrapper" class declares a brand new $_connected static property. This property is used within the "connect()" method to make sure that the connection to MySQL is established only once. With this simple approach, I'm getting the best of both worlds: on one hand, the method is only called on demand (read a lazy connection), while on the other hand, the connection is performed only once. As I said before, static properties can be really useful for improving the behavior of classes when used in a clever way; the code fragment illustrates this concept. Now that you've grasped how the enhanced version of the "MySQLiWrapper" class does its business, it's time to set up an example that shows it in action. This example will be coded in the following section, so click on the link below and read the lines to come.
blog comments powered by Disqus |
|
|
|
|
|
|
|