0

Is there a way to add an action to a CDbConnection when rollback action is called ?

I have this code and it works :

$transaction = $model->dbConnection->beginTransaction();

try {
    //...
    //doing some manipulations
    //...

    if($model->save()) {
        $transaction->commit();
        $this->redirect(array('view','id'=>$model->id));
    }

} catch(Exception $e) {
    $transaction->rollback();
    throw $e;
}

Is there a way reverting the manipulations done when the $transaction->rollback(); is called without putting this code in the catch statement, like adding an event on the transaction rollback function.

Maybe there's a workaround with Behaviours and Events, but I'm not sure how it works.

Thanks!

EDIT - What I want to do is this:

When the model fail to save, there will be a rollback on the database, but I'm doing some manipulations on the files too (that I need to do before validating & saving the model), so if the model fail to save because of the validation, I need to revert theses changes to the files.

Asgaroth
  • 4,274
  • 3
  • 20
  • 36
Philippe Boissonneault
  • 3,949
  • 3
  • 26
  • 33

1 Answers1

1

currently CDbTransaction does not have any events defined.

What I would do, is create class that will handle this logic in a way you can reuse:

//protected/components/AtomicTransformation.php
<?php
class AtomicTransformation {
  private $_model;
  private $_transaction;
  public function __contruct(CModel $model)
  {
    $this->_model = $model;
    $this->_transaction = $model->dbConnection->beginTransaction();
  }
  public function commit()
  {
    $this->_transaction->commit();
  }
  public function rollback( /* pass any params you need for your revert logic */)
  {
    // Do your revert logic here
    $this->_transaction->rollback();
  }
}

$transformation = new AtomicTransformation($model);

try {
    //...
    //doing some manipulations
    //...

    if($model->save()) {
        $transformation->commit();
        $this->redirect(array('view','id'=>$model->id));
    }

} catch(Exception $e) {
    $transformation->rollback( /*your params */ );
    throw $e;
}
Asgaroth
  • 4,274
  • 3
  • 20
  • 36