既然每个人都把他们的 OOP 扔进了擂台(注:我要做PDO,因为我更了解它,但原理是一样的,只是替换连接):
<?php
class DatabaseConnection
{
# Create a singleton to store the connection for reuse
private static $singleton,
$con;
# save connection to singleton and return itself (the full object)
public function __construct()
{
# If your singleton is not set
if(!isset(self::$singleton))
# assign it this class
self::$singleton = $this;
# return this class
return self::$singleton;
}
# This is a connection method because your __construct
# is not able to return the $pdo connection
public function connection($host='hostname',$username='username',$password='password',$database='database')
{
# In the connection, you can assign the PDO to a static
# variable to send it back if it's already set
if(self::$con instanceof \PDO)
return self::$con;
# If not already a PDO connection, try and make one
try {
# PDO settings you can apply at connection time
$opts = array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,PDO::ATTR_EMULATE_PREPARES => false);
# Assign your PDO Conneciton here.
self::$con = new PDO("mysql:host={$host};dbname={$database}",$username,$password,$opts);
# Return the connection
return self::$con;
}
catch (PDOException $e){
exit('Database error');
}
}
}
您可以在任何地方使用它,无论是在您的函数、类之内还是之外。它每次都会返回相同的连接。如果你使用spl_autoload_register()
使用自动加载功能,您将一切就绪,甚至不必显式使用require_once()
每次!
<?php
require_once('class.DatabaseConnection.php');
// Instantiate connection class
$pdo = new DatabaseConnection();
// Assign the connection to $con (or whatever variable you like)
$con = $pdo->connection();
需要注意的是,singleton
通常很少使用模式。通常最好使用new Objects()
而不分配它singleton
。我个人喜欢singleton
然而对于这个用途。
简单演示 - 考虑以下场景:
<?php
// Here is an example of the singlton with an echo
// which shows that the class is returning itself
// like a global
class DatabaseConnection
{
private static $singleton;
public function __construct()
{
// If your singleton is not set
if(!isset(self::$singleton)) {
echo 'NEW Object'.PHP_EOL;
// assign it this class
self::$singleton = $this;
}
else
echo 'SAME Object'.PHP_EOL;
// return this class
return self::$singleton;
}
}
function ReturnConnection()
{
return new DatabaseConnection();
}
class TestClass
{
public function __construct()
{
new DatabaseConnection();
}
}
function query($sql=false)
{
return ReturnConnection();
}
// The connection class wrapped in a function
$a = ReturnConnection();
// The function nested inside a class
$b = new TestClass();
// The function nested inside another function
$c = query();
上述用途singleton
将产生:
NEW Object
SAME Object
SAME Object