【发布时间】:2016-02-19 15:08:21
【问题描述】:
我有多个类方法,如果抛出异常,每个方法都使用事务和回滚。下面的基本示例。
class TaskMapper
{
private $dblayer;
public function __construct(PDO $dblayer)
{
$this->dblayer = $dblayer;
}
public function save(Task $task)
{
try {
$this->dblayer->beginTransaction();
$stmt = ... // query/queries here
$stmt->execute();
$stmt2 = ... // query/queries here
$stmt2->execute();
$this->dblayer->commit();
} catch (\PDOException $e) {
$this->dblayer->rollBack();
// deal with exception here
}
}
public function editField($id, $field, $value)
{
try {
$this->dblayer->beginTransaction();
$stmt = ... // query/queries here
$stmt->execute();
$stmt2 = ... // query/queries here
$stmt2->execute();
$stmt->execute();
$this->dblayer->commit();
} catch (\PDOException $e) {
$this->dblayer->rollBack();
// deal with exception here
}
}
}
现在,我正在为 cron 作业编写一个脚本,该脚本利用多个类方法,其中包含与上述类似的代码 - 具有事务和回滚以及异常。
例如:
if (date('j') == '1') {
// reset monthly count column
$task->editField(17, 'monthly_count', '0');
}
$task->save($task);
这是一个非常精简的示例,但我想知道是否可以将所有方法调用包装在 try/catch 块内的单个事务中,并在 catch 内回滚?那么将上面的代码包装在一个带有事务的 try/catch 中并在 catch 中回滚?
如果不是,那么处理这种情况的最佳方法是什么,如果一个方法调用失败,则必须回滚其他方法。
提前致谢。
【问题讨论】:
-
对我来说,save() 方法的存在意味着所有数据库事务都将从该调用中处理。到目前为止,更改仅在 php 对象级别完成。 save() 的作用是持久化更改,因此会将所有查询包装到单个事务中。
标签: php mysql pdo transactions