Overview
A transaction is a logical unit of work, a consistent and reliable portion of the execution of a program. The purpose of transactions is to achieve fault tolerance and concurrency. To ensure data integrity, access to persistent data needs to take place within a transaction.1)
Fault tolerance
Either all of a transaction’s changes to persistent memory are made successful, or none is made at all. If a failure occurs in the middle of a transaction, none of its database updates is made. This is the atomicity property of a transaction and is how fault tolerance is achieved.
Concurrency
Transactions also support concurrent accesses to persisted EZPDO objects by preventing one process’s updates from interfering with another process’s reads or updates. In other words, a transaction’s changes to persistent data are private and invisible to other processes until the entire transaction completes successfully, and other processes’ changes to persistent data are invisible to this transaction. This is the isolation property of transactions.
Usage examples
Example with auto-rollback
// get the EZPDO manager $m = epManager::instance(); // find an object using EZOQL $os = $m->find("from SomeClass as c where c.var = 'x'"); if (!$os) { echo "no object found\n"; exit(-1); } $o = $os[0]; // call manager to start transaction $m->start_t(); // change the value of var in object $o->var = 'y'; // end transaction with auto-rollback $m->commit_t(); // by default: auto-rollback // 'y' if transaction successful; 'x' if failed. echo $o->var;
Example without auto-rollback
// get the EZPDO manager $m = epManager::instance(); // find an object using EZOQL $os = $m->find("from SomeClass as c where c.var = 'x'"); if (!$os) { echo "no object found\n"; exit(-1); } $o = $os[0]; // call manager to start transaction $m->start_t(); try { // change the value of var in object $o->var = 'y'; // end transaction and save changed objects $m->commit_t(false); // false: no auto rollback } catch (Exception $e) { // something wrong. rollback to old values $m->rollback_t(); // do something here // ...... } // 'y' if transaction successful; 'x' if failed. echo $o->var;
API
The following are transaction methods provided through the EZPDO manager (epManager) runtime API.
- false|epTransaction start_t()
- Description: Start a transaction
- Parameter: none
- Return: bool
- void commit_t(boolean $rollback = true)
- Description: End a transaction
- Parameter: epTransaction $t
- Parameter: boolean $rollback (default to true)
- Return: void
- Throws Exception
- void rollback_t()
- Description: Abort a transaction and rollback
- Parameter: epTransaction $t
- Return: void