Want to have an Online Store but don't know where to start?
Click here and start selling online!

Using Transactions in PHP-ActiveRecord

December 31, 2011 | In: activerecord, closure, orm, phpactiverecord, transaction

Object Relational Mapping (ORM) is so popular these days because it makes the development really ‘agile’ and in PHP world, it’s not an exception. There are Doctrine, Propel and PHPActiverecord.

Object Relational Mapping (ORM) is so popular these days because it makes the development really ‘agile’ and in PHP world, it’s not an exception. There are Doctrine, Propel and PHPActiverecord.

I prefer PHPActiverecord because it is almost identical (about 95% IMO) with that with Ruby On Rails.

Enough for the introduction, let’s go back to our topic.

First, what is Transaction, according to wikipedia , “In computer science, transaction processing is information processing that is divided into individual, indivisible operations, called transactions. Each transaction must succeed or fail as a complete unit; it cannot remain in an intermediate state.”

In PHPAR, the transaction implementation is like this:

    Model::transaction($closure);

You will need to return false (when something goes wrong) and it will ‘rollback’, else it will ‘commit’ ¬†and proceed the process.

Inside the $closure is the actual code of transaction implementation.

Consider that we have 2 models, and we want to save in all of the three or nothing at all.

Say we have orders and payments table in our database that we want to have transaction into.

  Order::transaction(function() use ($order_data, $payment_data) {
	$order = Order::create($order_data);
	if(!$order)return false;
 
	$payment = Payment::create($payment_data);
	if(!$payment)return false;
  });
  return true;

And that’s it! Hope this helps.

Share on Facebook

Comment Form