PHP code example of maestrodimateo / simple-consul

1. Go to this page and download the library: Download maestrodimateo/simple-consul library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

maestrodimateo / simple-consul example snippets


use Maestrodimateo\SimpleConsul\Facades\Consul;

// Store & retrieve
Consul::put('config/app/name', 'My Application');
$name = Consul::get('config/app/name');

// Auto JSON encode/decode for arrays
Consul::put('config/database', ['host' => 'db.example.com', 'port' => 5432]);
$db = Consul::get('config/database');
echo $db['host']; // "db.example.com"

consul()->put('key', 'value');
consul()->get('key');

Consul::register();    // Register using config values
Consul::deregister();  // Remove from Consul

// app/Console/Kernel.php
$schedule->call(fn () => Consul::passCheck())->everyFifteenSeconds();

// config/consul.php
'health_check' => [
    'type' => 'script',
    'args' => ['php', 'artisan', 'health:check'],
    'interval' => '15s',
],

// Get with default
$debug = Consul::get('config/debug', false);

// Check existence
if (Consul::has('config/api-key')) { ... }

// Delete
Consul::delete('config/old-key');

// List keys
$keys = Consul::keys('config/');
// ["config/app/name", "config/database", ...]

// Register a service manually (with health check)
Consul::registerService(
    name: 'payment-api',
    port: 8080,
    tags: ['v2', 'production'],
    meta: ['version' => '2.1.0'],
    check: [
        'HTTP' => 'http://10.0.0.5:8080/up',
        'Interval' => '10s',
    ],
);

// List all services
$services = Consul::services();

// Get instances of a service
$instances = Consul::service('payment-api');

// Deregister
Consul::deregisterService('payment-api');

// Get healthy instances only
$healthy = Consul::healthyService('payment-api');

// Quick boolean check
if (Consul::isHealthy('payment-api')) {
    // At least one instance is passing
}

$result = Consul::withLock('jobs/send-emails', function () {
    // Runs only if the lock is acquired.
    // Lock is auto-released when done (even on exceptions).
    return sendEmails();
}, ttlSeconds: 30);

if ($result === false) {
    // Another process holds the lock
}

$sessionId = Consul::createSession(ttlSeconds: 60, name: 'my-lock');

if (Consul::acquireLock('my-resource', $sessionId)) {
    try {
        // critical section
    } finally {
        Consul::releaseLock('my-resource', $sessionId);
        Consul::destroySession($sessionId);
    }
}

Consul::kv();       // Consul\Services\KV
Consul::agent();    // Consul\Services\Agent
Consul::catalog();  // Consul\Services\Catalog
Consul::health();   // Consul\Services\Health
Consul::session();  // Consul\Services\Session

// config/consul.php
return [
    'address'    => env('CONSUL_HTTP_ADDR', 'http://127.0.0.1:8500'),
    'token'      => env('CONSUL_HTTP_TOKEN'),
    'datacenter' => env('CONSUL_DATACENTER'),
    'kv_prefix'  => env('CONSUL_KV_PREFIX', ''),

    'service' => [
        'enabled' => env('CONSUL_SERVICE_ENABLED', false),
        'id'      => env('CONSUL_SERVICE_ID', 'laravel-local'),
        'name'    => env('CONSUL_SERVICE_NAME', 'laravel'),
        'host'    => env('CONSUL_SERVICE_HOST', '127.0.0.1'),
        'port'    => (int) env('CONSUL_SERVICE_PORT', 8000),
        'tags'    => ['v1'],
        'meta'    => ['env' => 'production'],
    ],

    'health_check' => [
        'enabled'          => true,
        'type'             => 'http',          // http, tcp, script, ttl, grpc
        'endpoint'         => '/up',           // for http
        'interval'         => '15s',
        'timeout'          => '5s',
        'deregister_after' => '10m',
        'ttl'              => '30s',           // for ttl
        'grpc'             => null,            // for grpc
        'args'             => [],              // for script
    ],
];

// Same code, different namespaces:
Consul::get('database/host');
// production → reads "production/myapp/database/host"
// staging    → reads "staging/myapp/database/host"
bash
php artisan vendor:publish --tag=consul-config