PHP Database Singleton
The singleton design pattern is simple and useful. It limits the number of instances of an obect to just one. Using the singleton for a MySQL database connection is a limits the number of connections to only one which saves memory. This is done with a static private variable to store the only instance of the object. Also a public static method to create, store and return that single instance of the object that first time it is called, but just return the existing instance when called after the first time.
private static $instance;
public static function getInstance()
{
if (!self::$instance)
{
self::$instance = new Database();
}
return self::$instance;
}
What this static method does is create the instance by creating a instance of itself which calls a private __construct method setting the static instances value. The private constructor method then initiates a private connection variable which will be used by the reset of the methods in the database class. The four static variables used as the arguments to the mysqli constructor are inherited; this will make sense when you see all of the class’s code.
private static $instance = NULL;
private $connection;
private function __construct()
{
$this->connection = new mysqli(parent::host,parent::user,parent::pass,parent::name);
if (mysqli_connect_errno())
{
printf("Connection Error: %s\n ", mysqli_connect_error());
}
}
All together now. Now you want to add public methods for commonly needed database operations. For example to run queries on the database. The query method below returns the reference the result of the query provided in the argument.
<?php
class Config
{
const host = "localhost";
const user = "root";
const pass = "";
const name = "databasename";
}
class Database extends Config
{
private static $instance = NULL;
private $connection;
private function __construct()
{
$this->connection = new mysqli(parent::host,parent::user,parent::pass,parent::name);
if (mysqli_connect_errno())
{
printf("Connection Error: %s\n ", mysqli_connect_error());
}
}
public static function getInstance()
{
if (!self::$instance)
{
self::$instance = new Database();
}
return self::$instance;
}
public function real_escape_string($string)
{
return $this->connection->real_escape_string($string);
}
public function query($statement)
{
if($result = $this->connection->query($statement))
{
return $result;
}
else
{
printf("Errormessage: %s\n", $this->connection->error);
}
}
public function lastInsertID()
{
return $this->connection->insert_id;
}
private function __clone(){
}
}
?>
Here is how you would use this class to run a query.
<?php
include_once "Database.php";
$db= Database::getInstance();
$result= $db->query("SELECT * FROM Owner");
while ($row = mysqli_fetch_array($result))
{
print $row['OwnerNum'];
}
Design Patterns.