我有一个类,它使用PDO来处理数据库连接和查询。另一个类使用它的方法来连接数据库,获取或插入数据。我的问题是;
您是否认为最好初始化一个数据库对象并共享为全局var(干扰?),或者创建一个继承它的方法的子类(因此对于每个类都建立新的连接对象)? / p>
使用子类:
class database{
public function __construct(){
//connect database, save object to $this->con, catch exeptions
}
public function query($query, $data){
//prepare query, insert data, $this->con->exec(), return result
}
public function insert($tablename, $data){
//prepare insert query from assoc array in $data to $tablename and return PDO::statement
}
public function update($tablename, $query, $data){
//prepare update $query with given assoc array $data placeholder replaced for $tablename and return bool
}
public function delete($tablename, $query, $data = array()){
//prepare delete query, exec and return bool
}
}
class user extends database{
function register($data){
$this->insert('users', array(
'username' => 'abcdef',
'password' => password_hash($password, PASSWORD_DEFAULT)
));
}
function login($uname, $upass){
//blahblah
}
}
class content extends database{
//...
}
//more classes
$db = new database();
$user = new user();
如果我是$ db = new Database();和$ user = new user();一次打开两个连接。
使用共享对象(与上面相同的代码,除了扩展)
class database{
public function __construct(){
//connect database, save object to $this->con, catch exeptions
}
public function query($query, $data){
//prepare query, insert data, $this->con->exec(), return result
}
public function insert($tablename, $data){
//prepare insert query from assoc array in $data to $tablename and return PDO::statement
}
public function update($tablename, $query, $data){
//prepare update $query with given assoc array $data placeholder replaced for $tablename and return bool
}
public function delete($tablename, $query, $data = array()){
//prepare delete query, exec and return bool
}
}
class user{
public function __construct($con){
$this->con = $con;
}
function register($data){
$this->insert('users', array(
'username' => 'abcdef',
'password' => password_hash($password, PASSWORD_DEFAULT)
));
}
function login($uname, $upass){
//blahblah
}
}
class content{
public function __construct($con){
$this->con = $con;
}
//...
}
$db = new database();
$user = new user($db);
这种情况使用了一个对象,但我不确定,如果有不同操作的混合命令,那就不会有问题
$user->login();
$content->add();
$user->logout();
$stats->newReport();
你怎么看?此外,可能存在一些资源差异(用于保留对象的内存,处理器负载)提前感谢