我需要对一段代码使用事务,它由多个插入组成。在 try catch 块中包含整个代码块是否是一个好习惯,在 try..catch 块之前开始事务。然后对于任何捕获的异常回滚其他事务提交。
基本问题:
- 在单个事务周期内拥有整个代码块是不好的做法吗?
- 如果这是一种不好的做法,那么处理这个问题的好方法是什么?为什么?
这是一段代码:
$con = Propel::getConnection(SomeTablePeer::DATABASE_NAME);
$con->beginTransaction();
try {
$currentRevision = $budgetPeriod->getRevision();
$newRevision = $currentRevision->copy();
$newRevision->setIdclient($client->getIdclient());
$newRevision->setIsLocked(0);
$newRevision->save();
$currentRevision->setEffectiveTo($currentDate);
$currentRevision->save();
$currentRevisionHasCorporateEntities = $currentRevision->getCorporateEntitys();
$newOldCorporateEntitiesRelations = array();
foreach ($currentRevisionHasCorporateEntities as $currentRevisionHasCorporateEntity) {
$newRevisionHasCorporateEntity = $currentRevisionHasCorporateEntity->copy();
$newRevisionHasCorporateEntity->save();
}
// this continues for a while there are a whole list of insertions based on previous insertion and on and on.
}catch (Exception $exc) {
$con->rollback();
$this->getUser()->setFlashError('Error occured! Transaction Failed');
}