7

I have simple code which uses DB transaction in Yii2, this updates user balance and adds a new record to user balance history.

//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();
}

I should use DB transactions frequently to save data integrity. But handling DB transactions like above requires a lot of code lines, so I created the following function which mobilizes my codes:

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();
}

With this function I can handle transactions like this:

//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();
        }
    );
}

As you see the second way is very comfortable using transactions. But on this point, I am not sure that dbTransaction function works correctly or nor? Code review and notes which points potential issues are appreciated. Thanks

1

1 Answer 1

6

delete your code $transaction->rollBack(); before last line, because this code always rollback and canceling your transaction

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();
 }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.