用单例模式来设计一个PHP数据库类

最近感觉网站的数据库压力比较大,造成网站的速度下降得很厉害。因为有相当一部分的页面是直接连接数据库读数据的,所以把这部分的页面也改为使用数据库单例类来实现。现在基本都统一使用下面这个类来连接数据库了

  • 需要一个保存类的唯一实例的静态成员变量(通常$instance为私有变量)

  • 构造函数和克隆函数必须声明为私有的,为了防止外部程序new类从而失去单例模式意义

  • 必须提供一个访问这个实例的公共静态方法,从而返回唯一实例的一个引用

<?php
class nmdb 
{
	private $link;
	static private $_instance;
	// 连接数据库
	private function __construct($host, $username, $password)
	{
		$this->link = mysql_connect($host, $username, $password);
		$this->query("SET NAMES 'utf8'", $this->link);
		//echo mysql_errno($this->link) . ": " . mysql_error($link). "n";
		//var_dump($this->link);
		return $this->link;
	}
	
	private function __clone(){}
	
	public static function get_class_nmdb($host, $username, $password)
	{
        //$connector = new nmdb($host, $username, $password);
        //return $connector;
		
		if( FALSE == (self::$_instance instanceof self) )
		{
			self::$_instance = new self($host, $username, $password);
		}
		return self::$_instance;
    }
	
	// 连接数据表
	public function select_db($database)
	{
		$this->result = mysql_select_db($database);
		return $this->result;
	}
	
	// 执行SQL语句
	public function query($query)
	{
		return $this->result = mysql_query($query, $this->link);
	}
	
	// 将结果集保存为数组
	public function fetch_array($fetch_array)
	{
		return $this->result = mysql_fetch_array($fetch_array, MYSQL_ASSOC);
	}
	
	// 获得记录数目
	public function num_rows($query)
	{
		return $this->result = mysql_num_rows($query);
	}
	
	// 关闭数据库连接
	public function close()
	{
		return $this->result = mysql_close($this->link);
	}
	
}
?>

这个类的使用如下:

$connector = nmdb::get_class_nmdb($host, $username, $password);
$connector -> select_db($database);

下面的类也可以参考下:

<?php
/*
* mysql 单例
*/
class mysql{
    private $host    ='localhost'; //数据库主机
    private $user     = 'root'; //数据库用户名
    private $pwd     = ''; //数据库用户名密码
    private $database = 'imoro_imoro'; //数据库名
    private $charset = 'utf8'; //数据库编码,GBK,UTF8,gb2312
    private $link;             //数据库连接标识;
    private $rows;             //查询获取的多行数组
    static $_instance; //存储对象
    /**
     * 构造函数
     * 私有
     */
    private function __construct($pconnect = false) {
        if (!$pconnect) {
            $this->link = @ mysql_connect($this->host, $this->user, $this->pwd) or $this->err();
        } else {
            $this->link = @ mysql_pconnect($this->host, $this->user, $this->pwd) or $this->err();
        }
        mysql_select_db($this->database) or $this->err();
        $this->query("SET NAMES '{$this->charset}'", $this->link);
        return $this->link;
    }
    /**
     * 防止被克隆
     *
     */
    private function __clone(){}
    public static function getInstance($pconnect = false){
        if(FALSE == (self::$_instance instanceof self)){
            self::$_instance = new self($pconnect);
        }
        return self::$_instance;
    }
    /**
     * 查询
     */
    public function query($sql, $link = '') {
        $this->result = mysql_query($sql, $this->link) or $this->err($sql);
        return $this->result;
    }
    /**
     * 单行记录
     */
    public function getRow($sql, $type = MYSQL_ASSOC) {
        $result = $this->query($sql);
        return @ mysql_fetch_array($result, $type);
    }
    /**
     * 多行记录
     */
    public function getRows($sql, $type = MYSQL_ASSOC) {
        $result = $this->query($sql);
        while ($row = @ mysql_fetch_array($result, $type)) {
            $this->rows[] = $row;
        }
        return $this->rows;
    }
    /**
     * 错误信息输出
     */
    protected function err($sql = null) {
        //这里输出错误信息
        echo 'error';
        exit();
    }
}
//用例
$db = mysql::getInstance();
$db2 = mysql::getInstance();
$data = $db->getRows('select * from blog');
//print_r($data);
//判断两个对象是否相等
if($db === $db2){
    echo 'true';
}
?>

下面的也可以参考

<?php

class Db {
	static private $_instance;
	static private $_connectSource;
	private $_dbConfig = array(
		'host' => '127.0.0.1',
		'user' => 'root',
		'password' => '',
		'database' => 'video',
	);
     // //将构造方法私有,防止在外层直接new
	private function __construct() {
	}

	static public function getInstance() {
		if(!(self::$_instance instanceof self)) {
			self::$_instance = new self();
		}
		return self::$_instance;
	}

	public function connect() {
		if(!self::$_connectSource) {
			self::$_connectSource = @mysql_connect($this->_dbConfig['host'], $this->_dbConfig['user'], $this->_dbConfig['password']);	

			if(!self::$_connectSource) {
				throw new Exception('mysql connect error ' . mysql_error());
				//die('mysql connect error' . mysql_error());
			}
			
			mysql_select_db($this->_dbConfig['database'], self::$_connectSource);
			mysql_query("set names UTF8", self::$_connectSource);
		}
		return self::$_connectSource;
	}
}
/*$connect = Db::getInstance()->connect();

$sql = "select * from video";
$result = mysql_query($sql, $connect);
echo mysql_num_rows($result);
var_dump($result);*/



你可能感兴趣的:(用单例模式来设计一个PHP数据库类)