7

我有在 Yii2 中使用 DB 事务的简单代码,这会更新用户余额并在用户余额历史记录中添加一条新记录。

//User model
public function changeBalance(UserBalanceHistory $balance)
{
    $balance->balance = $this->balance;
    $balance->user_id = $this->id;
    $this->balance    = $this->getBalance() + $balance->getDelta();

    $transaction = Yii::$app->db->beginTransaction();
    try {
        if ($balance->save() && $this->save()) {
            $transaction->commit();
            return true;
        }
    } catch (Exception $e) {
        Yii::error($e->getMessage());
    }

    $transaction->rollBack();
}

我应该经常使用数据库事务来保存数据完整性。但是像上面这样处理数据库事务需要很多代码行,所以我创建了以下函数来调动我的代码:

function dbTransaction(callable $callback)
{
    $transaction = Yii::$app->db->beginTransaction();

    try {
        //if callback returns true than commit transaction
        if (call_user_func($callback)) {
            $transaction->commit();
            Yii::trace('Transaction wrapper success');
        }
    } catch (\Exception $e) {
        $transaction->rollBack();
        throw $e;
    }
    $transaction->rollBack();
}

使用此功能,我可以处理如下事务:

//User model
public function changeBalance(UserBalanceHistory $balance)
{
    dbTransaction(
        function () use ($balance) {
            $balance->balance = $this->balance;
            $balance->user_id = $this->id;
            $this->balance    = $this->getBalance() + $balance->getDelta();

            return $balance->save() && $this->save();
        }
    );
}

如您所见,第二种方式使用事务非常舒适。但是在这一点上,我不确定该dbTransaction功能是否正常工作?代码审查并指出哪些点潜在问题值得赞赏。谢谢

4

1 回答 1

6

$transaction->rollBack();在最后一行之前删除您的代码,因为此代码总是回滚并取消您的事务

function dbTransaction(callable $callback)
{
    $transaction = Yii::$app->db->beginTransaction();

    try {
        //if callback returns true than commit transaction
        if (call_user_func($callback)) {
            $transaction->commit();
            Yii::trace('Transaction wrapper success');
        }
    } catch (\Exception $e) {
        $transaction->rollBack();
        throw $e;
    }
    //$transaction->rollBack();
 }
于 2017-11-09T10:15:51.857 回答