在所有项目中只有一个mysql连接

时间:2013-03-14 05:42:46

标签: php mysql

我想知道是否有一种方法总是我有一个打开的连接到我的数据库。 我在我的网站上使用此代码:

mysql类

class Mysql{
public static $Server   = "localhost";
static $User = 'root';
static $Password = '';
static $DataBaseName = 'teca.v1';
static $Connection;
static $DataBase;
static $LoadConnection = 0;
static $CharSet = "utf8";

static $TRANS =false;
static $TRSS  = array();

public function __construct(){
    if(Mysql::$LoadConnection==0){
        Mysql::$Connection = mysql_connect(Mysql::$Server,Mysql::$User,Mysql::$Password);
        Mysql::$DataBase   = mysql_select_db(Mysql::$DataBaseName,Mysql::$Connection);
        $charset=Mysql::$CharSet;
        mysql_query("SET NAMES $charset");
        Mysql::$LoadConnection=1;
    }
}
}

模型类

class Model extends Mysql{
protected $datamembers = array();
protected $PrimaryKey="Id";
protected $TableName ="Table";
public $UnProtectedExecute = FALSE;

public  function ReadyString($value)
{
    if($this->UnProtectedExecute == TRUE)
        return addslashes($value);
    else
        return $value;
}
public function __set($variable, $value){
    $this->datamembers[strtolower($variable)] = $value;
}

public function __get($variable){
    return $this->datamembers[strtolower($variable)];
}

和我的一个对象:

class LibraryFiles extends Model{
    public $TableName   = 'library_files';
}

但我不知道这是对的,只是这段代码为我项目中的所有对象创建了1个连接?

2 个答案:

答案 0 :(得分:1)

您正在寻找什么是PHP Singleton数据库类。使用以下链接来获取想法。我想我不必在这里重复一遍。

http://www.matthewelliston.com/php-singleton-database-class/

Global or Singleton for database connection?

Creating the Singleton design pattern in PHP5

答案 1 :(得分:0)

你的设计没有多大意义。您应该为MySQLModel创建单独的类。 MySQL类应该实例化一次,并在整个脚本中使用。所以它应该只做一个连接。 然后让Model使用MySQL类的实例来操作数据。