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
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();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With