这里说一下关于使用数据库事务几项功能的改进。
首先,你现在可以像下面这样以回调形式的事务工作:
$connection->transaction(function(){
$order = new Order($customer);
$order->save();
$order->addItems($items);
});
这相当于下列冗长的代码:
$transaction = $connection->beginTransaction();
try {
$order = new Order($customer);
$order->save();
$order->addItems($items);
$transaction->commit();
} catch (Exception $e) {
$transaction->rollBack();
throw $e;
}
其它,事务可以触发一系列事件。 例如, a beginTransaction event is triggered by a DB connection when you start a new transaction; and a commitTransaction event is triggered when the transaction is successfully committed. You can respond to these events to perform some preprocessing and post-processing tasks when using transactions.
最后,开始一个新的事务时,您可以设置事务隔离级别(例如READ COMMITTED)。例如,
$transaction = $connection->beginTransaction(Transaction::READ_COMMITTED);
事务隔离级别 | 脏读 | 不可重复读 | 幻读 |
读未提交(read-uncommitted) | 是 | 是 | 是 |
不可重复读(read-committed) | 否 | 是 | 是 |
可重复读(repeatable-read) | 否 | 否 | 是 |
串行化(serializable) | 否 | 否 | 否 |