title: Wrapping class methods that use transactions
body: <p>I have multiple class methods that each use transactions and rollbacks if exceptions are thrown. Basic example below. </p>
  
  <pre><code>class TaskMapper
  {
      private $dblayer;
  
      public function __construct(PDO $dblayer)
      {
          $this-&gt;dblayer = $dblayer;
      }
  
      public function save(Task $task)
      {
          try {
              $this-&gt;dblayer-&gt;beginTransaction();
  
              $stmt = ... // query/queries here
              $stmt-&gt;execute();
  
              $stmt2 = ... // query/queries here
              $stmt2-&gt;execute();
  
              $this-&gt;dblayer-&gt;commit();
  
          } catch (\PDOException $e) {
  
              $this-&gt;dblayer-&gt;rollBack();
              // deal with exception here
          }
  
  
      }
  
      public function editField($id, $field, $value)
      {
          try {
              $this-&gt;dblayer-&gt;beginTransaction();
  
              $stmt = ... // query/queries here
              $stmt-&gt;execute();
  
              $stmt2 = ... // query/queries here
              $stmt2-&gt;execute();
  
              $stmt-&gt;execute();
  
              $this-&gt;dblayer-&gt;commit();
  
          } catch (\PDOException $e) {
  
              $this-&gt;dblayer-&gt;rollBack();
              // deal with exception here
          }
      }
  
  }
  </code></pre>
  
  <p>Now, I am writing a script for a cron job which utilises multiple class methods that contain code similar to the above - with transactions and rollbacks, and exceptions.</p>
  
  <p>For example:</p>
  
  <pre><code>if (date('j') == '1') {
      // reset monthly count column
      $task-&gt;editField(17, 'monthly_count', '0');
  }
  $task-&gt;save($task);
  </code></pre>
  
  <p>This is a very stripped back example, but I would like to know if it is possible to wrap all of the method calls within a single transaction within a try/catch block, and rollback within the catch? So wrap the code above in a try/catch with a transaction and a rollback in the catch?</p>
  
  <p>If not, what is the best way to approach a situation like this where if one method call fails, the others MUST be rolled back.</p>
  
  <p>Thanks in advance.</p>