Skip to content
Daniel Carbone edited this page Nov 6, 2026 · 1 revision

Txn

$consul->Txn wraps Consul's Transaction API. It runs a batch of KV, node, service and check operations atomically. For KV-only transactions you can also use $consul->KV->Txn (see KV).

Building operations

Each operation is a TxnOp with exactly one of KV, Node, Service or Check set:

TxnOp field Op class Verb enum
KV Txn\KVTxnOp Txn\KVOp (KVSet, KVGet, KVCAS, KVDelete, KVCheckNotExists, KVLock, ...)
Node Txn\NodeTxnOp Txn\NodeOp
Service Txn\ServiceTxnOp Txn\ServiceOp
Check Txn\CheckTxnOp Txn\CheckOp

The Verb parameters also accept the plain string value (e.g. 'set').

Reading the response

Txn() returns a TxnAPIResponse, which is not destructurable:

  • $resp->Err: transport or unexpected HTTP error.
  • $resp->OK: true if the transaction committed.
  • $resp->TxnResponse->Results: one TxnResult per operation (->KV, ->Node, ->Service, ->Check).
  • $resp->TxnResponse->Errors: when rolled back, one TxnError per failed op (->OpIndex, ->What).
  • $resp->QueryMeta
use DCarbone\PHPConsulAPI\Txn\KVOp;
use DCarbone\PHPConsulAPI\Txn\KVTxnOp;
use DCarbone\PHPConsulAPI\Txn\TxnOp;

$resp = $consul->Txn->Txn(
    null,
    new TxnOp(KV: new KVTxnOp(Verb: KVOp::KVGet, Key: 'txn/a')),
    new TxnOp(KV: new KVTxnOp(Verb: KVOp::KVCheckNotExists, Key: 'txn/a')),
);

if (null !== $resp->Err) {
    throw new RuntimeException((string)$resp->Err);
}

if (!$resp->OK) {
    foreach ($resp->TxnResponse->Errors as $e) {
        echo "op {$e->OpIndex}: {$e->What}\n"; // op 1: key "txn/a" exists
    }
} else {
    foreach ($resp->TxnResponse->Results as $result) {
        echo "{$result->KV->Key} = {$result->KV->Value}\n";
    }
}

A rolled-back transaction (HTTP 409) is reported through OK/Errors, not through Err.

See Responses and Errors.

Clone this wiki locally