Skip to content

Getting Started

Daniel Carbone edited this page Nov 6, 2026 · 2 revisions

Getting Started

Requirements

Installation

composer require dcarbone/php-consul-api:^v3.1

Creating a client

DCarbone\PHPConsulAPI\Consul is the entry point. It holds one instance of each API client.

use DCarbone\PHPConsulAPI\Config;
use DCarbone\PHPConsulAPI\Consul;

// Reads CONSUL_HTTP_ADDR, CONSUL_HTTP_TOKEN, etc., falling back to http://localhost:8500
$consul = new Consul();

// Explicit configuration
$consul = new Consul(config: new Config(
    Address: 'consul.example.com:8500',
    Scheme: 'https',
    Token: 'my-acl-token',
    Datacenter: 'dc1',
));

See Configuration for every option.

Clients are available as properties or methods:

$consul->KV;     // DCarbone\PHPConsulAPI\KV\KVClient
$consul->KV();   // same instance

First requests

use DCarbone\PHPConsulAPI\Agent\AgentServiceCheck;
use DCarbone\PHPConsulAPI\Agent\AgentServiceRegistration;
use DCarbone\PHPConsulAPI\KV\KVPair;

// Write a key
[$wm, $err] = $consul->KV->Put(p: new KVPair(Key: 'app/config/db', Value: 'postgres://localhost'));
if (null !== $err) {
    throw new \RuntimeException((string)$err);
}

// Read it back
[$pair, $qm, $err] = $consul->KV->Get(key: 'app/config/db');
if (null !== $err) {
    throw new \RuntimeException((string)$err);
}
if (null === $pair) {
    echo "key not found\n";
} else {
    echo $pair->Value, "\n";
}

// Which server is the leader?
[$leader, $err] = $consul->Status->Leader();

// Register a service with a TTL check on the local agent
$err = $consul->Agent->ServiceRegister(service: new AgentServiceRegistration(
    ID: 'web-1',
    Name: 'web',
    Port: 8080,
    Check: new AgentServiceCheck(TTL: '30s'),
));
$err = $consul->Agent->PassTTL(checkID: 'service:web-1', note: 'ready');

// Find healthy instances
[$entries, $qm, $err] = $consul->Health->Service(service: 'web', passingOnly: true);
foreach ($entries as $entry) {
    echo "{$entry->Service->Address}:{$entry->Service->Port}\n";
}

Conventions

  • Errors are returned, not thrown. Every call returns an error value (null on success). See Responses and Errors.
  • Named parameters. Methods and model constructors are designed to be called with named arguments. The parameter names of model constructors match the Consul field names (Key:, Value:, ModifyIndex:).
  • Options are trailing arguments. Where the Go client has Get(key, q *QueryOptions), this library has Get(key: ..., opts: new QueryOptions(...)). See Query and Write Options.
  • uint64 values are BigIntegers. See Big Integers.
  • Durations are DCarbone\Go\Time\Durations. See Durations and Time.

Clone this wiki locally