Rediska

Follow me on twitter…

Transactions

Transaction allows you to execute a set of commands as a single atomic command and guarantees all of them will be successfully executed:

<?php

// Initialize Rediska
$rediska = new Rediska();

// Initialize transaction, add command and execute
$rediska->transaction()->set('a', 1)
                       ->get('a', 1)
                       ->delete('a')
                       ->execute();

// Commands executed on server on transaction execution

// Initialize transaction
$transaction = $rediska->transaction();

// Add command to transaction
$transaction->set('a', 1);

// Key 'a' doesn't exists because transaction not executed
print $rediska->exists('a'); // #=> false

// Execute transaction
$transaction->execute();

// Key 'a' exists
print $rediska->exists('a') // #=> true

// You may discard transaction
$transaction = $rediska->transaction();
$transaction->set('a', 1)
            ->get('a', 1);
            ->delete('a', 1);

if (/* something wrong */) {
    $transaction->discard();
}

?>

Transaction also support optimistic locking (check-and-set). Let's try implement atomic increment for example:

<?php

function increment(Rediska $rediska, $key) {
 // Create new transaction
 $transaction = $rediska->transaction();

 // Watch for a key or array of keys
 $transaction->watch($key);

 // Get key value
 $count = $rediska->get($key);

 // Increment
 $count++;

 // Set new value in transaction
 $transaction->set($key, $count);

 // Execute
 try {
     $transaction->execute();
 } catch(Rediska_Transaction_AbortedException $e) {
     return increment($rediska, $key);
 }

 return $count;
}

$rediska = new Rediska();
increment($rediska, 'count');

?>

If someone change key count between watch() and execute() transaction throws a Rediska_Transaction_AbortedException.

Comments

Fork me on GitHub