Skip to content
Yo-An Lin edited this page May 17, 2017 · 1 revision

The repository class provides methods for handling transactions. These methods are actually wrapper methods of PDO::beginTransaction, PDO::commit, PDO::rollback.

Since the repository class separates the read/write behavior, these methods only works for "write" connection:

use AuthorBooks\Model\Author;

$authorRepo = Author::masterRepo();

$ret = $authorRepo->create([
    'name' => 'Elon Musk',
    'email' => 'elon@boring',
    'identity' => 'elon',
]);
$this->assertResultSuccess($ret);  // This checks $ret->success

// Now let's begin the transaction
$repo->begin();

// Select the row with SELECT FOR UPDATE  (MySQL only)
$a2 = $repo->loadForUpdate([ 'identity' => 'elon' ]);

// the $a2 variable now holds the row of "Elon Musk", let's update the name
$ret = $a2->update(['name' => 'Mars']);
$this->assertResultSuccess($ret);

// assert if we're in the transaction
$this->assertTrue($repo->inTransaction());

// commit if you want this update
$this->assertTrue($repo->commit());

// rollback if you don't want this update.
$this->assertTrue($repo->rollback());