Answer the question
In order to leave comments, you need to log in
How to organize transactions in Yii2 without code repetition?
The situation is this, for example, in my admin panel, every action is monitored. That is, if I create or delete a page, records about this fly to the admin monitoring. This means that I need a transaction in each action.
Writing similar code in every action is not an option.
$transaction = $connection->beginTransaction();
try {
...
$transaction->commit();
} catch (Exception $e) {
$transaction->rollBack();
}
Answer the question
In order to leave comments, you need to log in
You can use the solution in the forehead.
protected function inTransaction($fn) {
$connection = ...
$transaction = $connection->beginTransaction();
$result = false;
try {
$result = call_user_func($fn);
$transaction->commit();
} catch (Exception $e) {
$transaction->rollBack();
}
return $result;
}
$result = $this->inTransaction(function() use ($data) {
...
});
$result = $this->inTransaction(array('ClassName', 'methodName'));
I would not push transactions everywhere where it is not necessary.
Well, if you need it, then yes, you can do it through events, for this they are intended.
Create a base controller for yourself and inherit it for everyone else
public function init()
{
parent::init();
$this->on(Controller::EVENT_AFTER_ACTION,[$this,'onAfterAction']);
$this->on(Controller::EVENT_BEFORE_ACTION,[$this,'onBeforeAction']);
}
public function onAfterAction()
{
print "onAfterAction ";
}
public function onBeforeAction()
{
print "onBeforeAction ";
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question