Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Db Transactions in Yii2 with callbacks

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

like image 709
complex Avatar asked Oct 09 '15 11:10

complex


1 Answers

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();
 }
like image 183
jack Avatar answered Nov 18 '22 23:11

jack