我想知道是否有一种方法,总是我有一个打开的连接到我的数据库。我在我的网站中使用这些代码:
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连接的所有对象在我的项目?
你正在寻找一个PHP单例数据库类。使用下面的链接来了解这个想法。我想我不必在这里重复了。
http://www.matthewelliston.com/php-singleton-database-class/全局还是单例数据库连接?
在PHP5中创建单例设计模式
你的设计不太有意义。您应该为MySQL
和Model
分别创建类。MySQL
类应该实例化一次,并在整个脚本中使用。所以它应该只有一个连接。然后让Model
使用MySQL
类的实例对数据进行操作。