N
N
nepster-web2014-04-11 03:10:41
Yii
nepster-web, 2014-04-11 03:10:41

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

I've heard something about events, or maybe somehow you can do such a thing with the help of behaviors, in general, please tell me how to make a transaction for all actions?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
Damir Makhmutov, 2014-04-11
@doodoo

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

Usage:
$result = $this->inTransaction(function() use ($data) {
    ...
});

$result = $this->inTransaction(array('ClassName', 'methodName'));

I haven't tested it for functionality :-)

A
Alexander N++, 2014-04-13
@sanchezzzhak

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 question

Ask a Question

731 491 924 answers to any question