我有多个类方法,每个方法在引发异常时都使用事务和回滚。下面的基本示例。包装使用事务的类方法
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块中的单个事务中的所有方法的调用,在捕获中回滚?因此,将上面的代码封装在一个try/catch中,并在catch中使用事务和回滚?
如果不是,处理这种情况的最好方法是如果一个方法调用失败,其他方法必须回滚。
在此先感谢。
对于我来说,save()方法的存在意味着所有数据库事务都将从该调用中处理。到那时为止,变化只在php对象级别完成。 save()的作用是保持更改并因此将所有查询包装到单个事务中。 – Shadow