以下是之前自己用到的数据库连接单例模式,具体如下:
<?php
/**
* Created by JetBrains PhpStorm.
* User: yang
* Date: 7/18/12
* Time: 2:11 PM
* To change this template use File | Settings | File Templates.
*/
include_once"../../../lib/Log4PHP/Log4PHP.php";
include_once"../../common/poolConnect.php";
class dbUtil
{
//数据库连接实例
private static $dbConn_ = null;
//将构造函数设置为private,防止外部过度实例化
private function __construct()
{
//创建一个数据库连接
return @poolConnect();
}
//将__clone函数设置为private,防止外部克隆
private function __clone()
{
}
//获取数据库连接实例
public static function getDbConn()
{
//如果数据库连接实例为空
if(!self::$dbConn_)
{
//创建数据库连接实例
self::$dbConn_ = new dbUtil();
//如果创建失败记录相应的信息
if (!self::$dbConn_)
{
Log4PHP::getLogger("dbUtil")
->error("getDbConn -- the connection of database fails (log by yang)");
$oci_errorMessage = oci_error()['message'];
Log4PHP::getLogger("dbUtil")
->error("getDbConn -- oci_error is". $oci_errorMessage. "(log by yang)");
throw new Exception("抱歉!系统数据库连接异常");
}
}
return self::$dbConn_ ;
}
//关闭数据库连接实例
public static function closeDbConn()
{
if(self::$dbConn_)
{
//关闭数据库连接
$dbCloseResult = @oci_close(self::$dbConn_);
//如果数据库关闭失败记录相应信息
if( !$dbCloseResult )
{
Log4PHP::getLogger("dbUtil") ->error("closeDbConn -- close the database fails (log by yang)");
$oci_errorMessage = oci_error()['message'];
Log4PHP::getLogger("dbUtil")->error("closeDbConn -- oci_error is $oci_errorMessage (log by yang)");
throw new Exception("抱歉!系统数据库关闭异常");
}
return true;
}
return false;
}
}