You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

37 lines
809 B

7 years ago
<?php
namespace core\services;
use core\dispatchers\DeferredEventDispatcher;
3 years ago
use Exception;
use Yii;
7 years ago
class TransactionManager
{
3 years ago
private DeferredEventDispatcher $dispatcher;
7 years ago
public function __construct(DeferredEventDispatcher $dispatcher)
{
$this->dispatcher = $dispatcher;
}
3 years ago
/**
* @param callable $function
* @throws \yii\db\Exception
*/
7 years ago
public function wrap(callable $function): void
{
3 years ago
$transaction = Yii::$app->db->beginTransaction();
7 years ago
try {
$this->dispatcher->defer();
$function();
$transaction->commit();
$this->dispatcher->release();
3 years ago
} catch (Exception $e) {
7 years ago
$transaction->rollBack();
$this->dispatcher->clean();
throw $e;
}
}
3 years ago
}