【发布时间】:2014-05-08 08:10:48
【问题描述】:
我有一个封装 PDO 的类,定义为该示例:
class db{
private $conn=null;
function __construct(){
getConn();
}
function getConn(){
$this->conn = new PDO("mysql:host=localhost;dbname=database", 'username', 'password');
}
}
我想在不同的类实例之间重用相同的数据库连接,这样我就可以在复杂的操作中使用事务,例如:
function getDataFromAnotherTable(){
$db = new dbClass;
$data = execute('select * from table2');
return $data;
}
//main code start here...
$db = new db; //here i will instantiate class defined above
$db->beginTrans();
$db->execute(insert into table1);
//here transaction still active
$data = getDataFromAnotherTable()
//now transaction has been closed by previous call!
$db->execute('insert into table1');
//here i receive "There is no active transaction" error because transaction is closed inside
// getDataFromAnotherTable()
$db->endTransaction();
我想改变我的班级:
function __construct(){
if(empty($this->conn){
getConn();
}
}
所以如果一个连接已经存在,将被重用并且不会创建新的连接。 我已经尝试过这种方法,但是类的每个实例都会获得新的连接,所以我不能重用相同的连接来维护我对不同类和函数的事务。
请记住,这只是一个简化的示例!我的情况真的更复杂,所以我不能使用类似的东西做一个插入语句:
select x from table1 insert into table2
提前感谢您的支持!
【问题讨论】:
-
这种封装没有多大意义。
-
嗨,感谢您的评论,但正如我在帖子中所说,这只是一个真正的简化示例。我的 DB 类不仅用于连接,还涵盖了许多其他问题。那么,您需要更多信息来帮助我,或者您认为这不可能实现我的目标?
-
恐怕它主要解决不存在的问题,就像大多数 PHP 代码一样
-
您的问题有非常简单的解决方案。只需启动一次数据库连接,然后一直使用它。就是这样
标签: php pdo transactions