Home arrow PHP arrow Page 3 - Improving MySQL Connection with Static Variables in PHP 5 Classes

Connecting to MySQL only once - PHP

In this third part of a four-part series on static variables, I show how to use another static property in the previous MySQL driver to connect “more cleverly” to the database server. This example demonstrates how powerful a property like this can be, when utilized in an effective manner.

TABLE OF CONTENTS:
  1. Improving MySQL Connection with Static Variables in PHP 5 Classes
  2. Review: the previous MySQL driver's classes
  3. Connecting to MySQL only once
  4. A final example
By: Alejandro Gervasio
Rating: starstarstarstarstar / 3
December 29, 2009

print this article
SEARCH DEV SHED

TOOLS YOU CAN USE

advertisement

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.



 
 
>>> More PHP Articles          >>> More By Alejandro Gervasio
 

blog comments powered by Disqus
escort Bursa Bursa escort Antalya eskort
   

PHP ARTICLES

- Hackers Compromise PHP Sites to Launch Attac...
- Red Hat, Zend Form OpenShift PaaS Alliance
- PHP IDE News
- BCD, Zend Extend PHP Partnership
- PHP FAQ Highlight
- PHP Creator Didn't Set Out to Create a Langu...
- PHP Trends Revealed in Zend Study
- PHP: Best Methods for Running Scheduled Jobs
- PHP Array Functions: array_change_key_case
- PHP array_combine Function
- PHP array_chunk Function
- PHP Closures as View Helpers: Lazy-Loading F...
- Using PHP Closures as View Helpers
- PHP File and Operating System Program Execut...
- PHP: Effects of Wrapping Code in Class Const...

Developer Shed Affiliates

 


Dev Shed Tutorial Topics: