/News

Creating a MySQL Database Class Using the Singleton Design Pattern

Source:thatspoppycock   2009-09-22    Comments:0  Click:

Introduction

Using the Singleton Pattern is a simple way to limit the number of instances of an object to just one, helps keep database connections organized, and saves memory. We will save details on the abstractions of the Singleton Pattern, and limit explanation to the code on this page used to create the mysqli_database object.

MySQL database class code

The code below is a basic example of how to use the Singleton Pattern to create a database class. This concept makes it easy to stay organized and use a centralized object for all of your database connections. Keep in mind that this is only a very basic level example, and there are many things that can be done to improve this class. Some functionality we will add in later parts of this tutorial include:

  • Multiple database connections (simultaneous)
  • Result caching
<?php
/**
 * MySQLi database class using Singleton Pattern
 *
 * @package tpc_tutorials
 * @version 0.1.1 20090311T19:4800-05:00
 * @author  Chris Strosser
 * @link    http://dev.thatspoppycock.com/
 *
 * @use	This class requires PHP5 to use.
 *
 *	$db = mysqli_database::instance();
 *	$db->connect(DB_HOSTNAME, DB_USERNAME, DB_PASSWORD, DB_DATABASE);
 *	$result = $db->query("SELECT * FROM example WHERE id = '1'");
 *	$db->close();
 *
 */
class mysqli_database {
	/**
	 * Database connection object
	 *
	 * @access private
	 * @var object
	 */
	private $mysqli;
 
	/**
	 * Instance of database object
	 *
	 * @access private
	 * @var object
	 */
	private static $db_instance;
 
	/**
	 * Constructor
	 *
	 * @access private
	 * @note Making the constructor private blocks this from being directly created
	 */
	private function __construct() {}
 
	/**
	 * Creates/references database class instance
	 *
	 * @access public
	 * @return object
	 */
	public static function instance() {
		if (!self::$db_instance) {
			self::$db_instance = new mysqli_database();
		}
		return self::$db_instance;
	}
 
	/**
	 * Connect to the MySQL database
	 *
	 * @access public
	 * @param string $host		Database hostname
	 * @param string $user		Database username
	 * @param string $password	Database password
	 * @param string $name		Database name
	 * @return void
	 */
	public function connect($host, $user, $password, $name) {
		# Connect to database
		$this->mysqli = new mysqli($host, $user, $password, $name);
		# Check connection
		if (mysqli_connect_errno()) {
			printf("Error connecting to database: %s", mysqli_connect_error());
			exit();
		}
	}
 
	/** 
	 * Close connection to MySQL database
	 *
	 * @access public
	 * @return void
	 */
	public function close() {
		$this->mysqli->close();
	}
 
	/**
	 * Execute query and return results
	 *
	 * @access public
	 * @param string $sql MySQL statement to execute
	 * @return mixed
	 */
	public function query($sql) {
		if (!$result = $this->mysqli->query($sql)) {
			return false;
		} else {
			return $result;
		}
	}
 
	/**
	 * Make data safe for database
	 *
	 * @access public
	 * @param string $data Data to be escaped
	 * @return string Sanitized data
	 */
	public function escape($data) {
		return $this->mysqli->real_escape_string($data);
	}
 
	/**
	 * Prevent cloning of this class
	 *
	 * @access public
	 * @return void
	 */
	public function __clone() {
		# Issue E_USER_ERROR if clone attempted
		trigger_error('Cloning <em>mysqli_database</em> is forbidden.', E_USER_ERROR);
	}
 
	/**
	 * Destructor (Close database connection)
	 *
	 * @access public
	 * @return void
	 */
	public function __destruct() {
		$this->mysqli->close();
	}
}
?>
Computer Tutorials
Download: Realtek HD Audio 2.33 driver
The latest download of Realtek's HD audio driver version available for Windows XP and Vista, it runs under Windows 7 too.  full story
Download: ATI Catalyst 9.9
ATI just released ATI Catalyst 9.9 for Windows 7,Windows Vista, Windows XP.  full story
Intel Core i5, Core i7 800 Processors and P55 Express
With today's launch of their new Lynnfield based Core i5 and i7 800 series processors, and the accompanying P55 Express chipset  full story
Download: Realtek HD Audio 2.32
The latest download of Realtek's HD audio driver version available for Windows XP and Vista, it runs under Windows 7 too  full story
Download:NVIDIA SLI Profile update V2.0
This version of the NVIDIA profile update should be used with v190.62 WHQL display driver.  full story
LG BL40 New Chocolate preview
The words Black Label evoke images of things exclusive, reserved for the lucky few  full story
Gigabyte GA-EX58-UD3R (rev. 1.6) review
This mainboard is especially interesting because it is the junior model in the Gigabyte lineup on Intel X58 Express chipset  full story
Home  |  Notebook  |  Bios  |  Display  |  Sound  |  Printer  |  Dell drivers  |  HP drivers  |  Intel  |  Apple
Sony  |  Canon  |  Software  |  PDA  |  News  |  Forum
?2009 Driversdown.com. All Rights Reserved.