Repository navigation
Txn
Daniel Carbone edited this page Nov 6, 2026
·
1 revision
$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).
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').
Txn() returns a TxnAPIResponse, which is not destructurable:
-
$resp->Err: transport or unexpected HTTP error. -
$resp->OK:trueif the transaction committed. -
$resp->TxnResponse->Results: oneTxnResultper operation (->KV,->Node,->Service,->Check). -
$resp->TxnResponse->Errors: when rolled back, oneTxnErrorper 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.