views:

40

answers:

1

If i’ve got 2(or more) model methods which do (for example, in billing system) enrolling/withdrawing, and one controller’s method that calls 2(or more) of these model methods.

Is it a good way(maybe, any suggestions how to do it better) to write/use 2model methods like these:

public function start_transaction(){
    $this->db->trans_start();
}

public function end_transaction(){
   $this->db->trans_complete();
} 

And call in controller’s method:

   public function smth(){
       //something
       $this->model->start_transaction();
       $this->model->enroll();
       //something else
       $this->model->withdraw();
       $this->model->end_transaction();
   } 

Will transaction be reversed, if model's withdraw() method fails?

Thanks.

+1  A: 

I'm fairly new to CodeIgniter, but I've been doing a fair amount of transactional work in my project.

However, I've been using the DataMapper Overzealous ORM library - and handling transactions using that code library.

So DMZ code I've been writing (caution - may not be best practice) would look something like:

public function smth() {
  $model->trans_begin();
  // assuming method returns boolean
  $enroll_success = $model->enroll();
  //something else
  // assuming method returns boolean
  $withdraw_success = $model->withdraw();
  if ($enroll_success && $withdraw_success && $model->trans_status() === TRUE)
  {
    $model->trans_commit();
  }
  else
  {
    $model->trans_rollback();
  }
}

I'm also assuming that the "something else" happening in your controller prevents you from creating a single method in your model that would just handle both the enroll & withdraw functions in a transaction.

someoneinomaha
Thanks. Yes, i can't use a single method (otherwise- i didn't ask such dumb questions :)).One more question: using standard CI's active record, it seems i can't call(from controller's method) - like you do - $model->trans_begin(). ? (so, am i 'doomed' to use additional functions - like in my question?)
DCrystal
I figured... though since I started this project, all I feel like I've been doing is asking dumb questions so thought I would double check. :) In the end, isn't the DMZ $model->trans_begin() the same thing as you having a separate method in your model start_transaction()? I adopted DMZ pretty quickly, so I don't have as much experience with just straight CI active record, but it seems like it would work. Do you have a sandbox where you could do some testing with this?
someoneinomaha
Yes, i've got sandbox and will test it.Thanks for the help.
DCrystal
Sure... would you mind posting your results back here? I'd like to have a better understanding of how the standard CI Active Record system would work in this situation.
someoneinomaha
Of course, if it makes sense. //not sure - i might post it as comment (or answer)?
DCrystal