我想知道是否有可能在每个事务的基础上设置PDO::ATTR_ERRMODE,而不是每个连接的基础。
我在class Database
中打开一个数据库连接,目前正在那里设置属性:
namespace Core {
class Database {
private $pdo;
public function __construct() {
$this->pdo = new 'PDO(/*Connection arguments*/);
$this->pdo->setAttribute('PDO::ATTR_ERRMODE, 'PDO::ERRMODE_EXCEPTION);
}
public function getConnection() {
return $this->pdo;
}
}
}
现在所有的错误都会抛出异常,然而,我只希望在处理手动事务时这种行为。
理想情况下,我可以这样做:
namespace Repositories {
class Something {
private $pdo;
public function __construct('Core'Database $database) {
$this->pdo = $database->getConnection();
}
public function doSomething() {
$this->pdo->setAttribute('PDO::ATTR_ERRMODE, 'PDO::ERRMODE_EXCEPTION); // Set the attribute here
$this->pdo->beginTransaction();
try {
// Execute some queries and statements
$this->pdo->commit();
}
catch ('PDOException $e) {
$this->pdo->rollback();
// Do something with $e
}
}
}
}
对于在方法结束时返回其默认的错误模式(我知道我的例子不会工作)
Thanks in advance
您可能需要知道,我并没有在每个使用PDO连接的方法中创建新的PDO连接,但是Database类在第一次创建时存储在对象池中。
您可以这样做:
$pdo = $this->pdo;
$pdo->setAttribute('PDO::ATTR_ERRMODE, 'PDO::ERRMODE_EXCEPTION);