Search code examples
phpdatabasetransactionskohanakohana-orm

How to manage DB transactions in Kohana / PHP elegantly


I'm new to Kohana but come from a Spring/Java background.

In Spring I'm used to all service methods automatically having DB transactions applied to them. I just tag the method to indicate whether it only needs a read transaction or read/write.

What do people do in this regard in Kohana? A new app I'm working with doesn't have transactions except manually in a few places where they know it's necessary. To me this seems a bit risky, it's easy to overlook some transactional consistency requirement, it was always nice to have that globally enforced in Spring.


Solution

  • Here is how I deal with it:

    1. Create a base class for all service method classes:

      abstract class Base
      {
      
          public function __call($method,$arguments)
          {
                  // Start transaction here
                  echo 'start';
      
                  try
                  {                    
                      call_user_func_array(array($this, $method), $arguments);
      
                      // Commit
                      echo ' commit';
                  }
                  catch ($e)
                  {
                      // Roll back
                  }                       
          }
      
      }
      
    2. Create a child class with all "protected" functions:

      class Member extends Base
      {
              protected function test()
              {
                  echo 'test';
              }
      }
      
    3. Call service method:

      $member = new Member();
      
      $member->test();
      

    It will display: "start test commit"

    The trick here is you will have to use "protected" for all your functions, if not it will no longer run (it will call the "test" function directly, not through __call().