PHPackages                             maestrodimateo/simple-consul - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. maestrodimateo/simple-consul

ActiveLibrary

maestrodimateo/simple-consul
============================

A simple, elegant Laravel wrapper for HashiCorp Consul

v1.2.0(1mo ago)117↑429.4%MITPHPPHP ^8.3 || ^8.4

Since Apr 5Pushed 1w agoCompare

[ Source](https://github.com/maestrodimateo/simple-consul)[ Packagist](https://packagist.org/packages/maestrodimateo/simple-consul)[ RSS](/packages/maestrodimateo-simple-consul/feed)WikiDiscussions main Synced 1mo ago

READMEChangelogDependencies (5)Versions (5)Used By (0)

Simple Consul
=============

[](#simple-consul)

[![Latest Version on Packagist](https://camo.githubusercontent.com/da2bf66755b86b87ab59880a99fd74ec8580c04b6166c597a47ca5897ee7b14d/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f6d61657374726f64696d6174656f2f73696d706c652d636f6e73756c2e737667)](https://packagist.org/packages/maestrodimateo/simple-consul)[![License](https://camo.githubusercontent.com/e3770d1f88d1688bf7df4714a310d330062eb824e6e431e7cf8a2a9d7c823c5c/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f6c2f6d61657374726f64696d6174656f2f73696d706c652d636f6e73756c2e737667)](https://packagist.org/packages/maestrodimateo/simple-consul)

A simple, elegant Laravel wrapper for [HashiCorp Consul](https://www.consul.io/).

Built on top of [friendsofphp/consul-php-sdk](https://github.com/FriendsOfPHP/consul-php-sdk), this package provides a clean Facade and helper for KV store, service discovery, health checks, and distributed locking — without dealing with raw HTTP responses.

Installation
------------

[](#installation)

```
composer require maestrodimateo/simple-consul
```

Publish the config:

```
php artisan vendor:publish --tag=consul-config
```

Quick Start
-----------

[](#quick-start)

Add to your `.env`:

```
CONSUL_HTTP_ADDR=http://127.0.0.1:8500
CONSUL_HTTP_TOKEN=your-acl-token        # optional
CONSUL_KV_PREFIX=myapp/production/      # optional
```

```
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"
```

The `consul()` helper is also available:

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

---

Auto Service Registration
-------------------------

[](#auto-service-registration)

The package can automatically register your application with Consul on boot. Just set the env variables — **zero PHP code needed**:

```
CONSUL_SERVICE_ENABLED=true
CONSUL_SERVICE_NAME=payment-api
CONSUL_SERVICE_HOST=10.0.0.5
CONSUL_SERVICE_PORT=8080
CONSUL_SERVICE_TAGS=v2,production
```

The service registers on every boot (idempotent) and Consul's health check handles cleanup when the app goes down — no deregister needed.

### Manual register/deregister

[](#manual-registerderegister)

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

---

Health Check Types
------------------

[](#health-check-types)

Configure the check type via `CONSUL_HEALTH_CHECK_TYPE`. Default is `http`.

### HTTP (default)

[](#http-default)

Consul polls an endpoint on your app:

```
CONSUL_HEALTH_CHECK_TYPE=http
CONSUL_HEALTH_CHECK_ENDPOINT=/up
CONSUL_HEALTH_CHECK_INTERVAL=15s
CONSUL_HEALTH_CHECK_TIMEOUT=5s
```

### TCP

[](#tcp)

Consul checks that the port accepts connections:

```
CONSUL_HEALTH_CHECK_TYPE=tcp
```

### gRPC

[](#grpc)

For gRPC services:

```
CONSUL_HEALTH_CHECK_TYPE=grpc
CONSUL_HEALTH_CHECK_GRPC=127.0.0.1:8080/my.service
```

### TTL

[](#ttl)

Your app sends periodic heartbeats. Consul marks the service as critical if no heartbeat is received within the TTL:

```
CONSUL_HEALTH_CHECK_TYPE=ttl
CONSUL_HEALTH_CHECK_TTL=30s
```

Call `passCheck()` periodically (e.g., in the scheduler):

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

### Script

[](#script)

Consul runs a command to check health:

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

---

KV Store
--------

[](#kv-store)

```
// 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", ...]
```

---

Service Discovery
-----------------

[](#service-discovery)

```
// 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');
```

---

Health Checks
-------------

[](#health-checks)

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

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

---

Distributed Locking
-------------------

[](#distributed-locking)

### With callback (recommended)

[](#with-callback-recommended)

```
$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
}
```

### Manual lock management

[](#manual-lock-management)

```
$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);
    }
}
```

---

Raw SDK Access
--------------

[](#raw-sdk-access)

For advanced use cases, access the underlying SDK services directly:

```
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
```

---

Configuration
-------------

[](#configuration)

```
// 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
    ],
];
```

### KV Prefix

[](#kv-prefix)

The `kv_prefix` is prepended to all KV operations automatically:

```
# .env.production
CONSUL_KV_PREFIX=production/myapp/

# .env.staging
CONSUL_KV_PREFIX=staging/myapp/
```

```
// Same code, different namespaces:
Consul::get('database/host');
// production → reads "production/myapp/database/host"
// staging    → reads "staging/myapp/database/host"
```

---

Testing
-------

[](#testing)

```
# Unit tests (no Consul needed)
./vendor/bin/pest tests/Unit

# Integration tests (requires Consul on 127.0.0.1:8500)
./vendor/bin/pest --group=integration
```

---

License
-------

[](#license)

MIT

Credits
-------

[](#credits)

- [Noel Mebale](https://github.com/maestrodimateo)
- Built on [friendsofphp/consul-php-sdk](https://github.com/FriendsOfPHP/consul-php-sdk)

###  Health Score

44

—

FairBetter than 92% of packages

Maintenance96

Actively maintained with recent releases

Popularity10

Limited adoption so far

Community6

Small or concentrated contributor base

Maturity54

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~0 days

Total

4

Last Release

35d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/92a2c64304e341345f2854b5bc9c43806b9e54f0b5b9b57135d37d69dd7c5c67?d=identicon)[mebalenoel](/maintainers/mebalenoel)

---

Top Contributors

[![maestrodimateo](https://avatars.githubusercontent.com/u/40523415?v=4)](https://github.com/maestrodimateo "maestrodimateo (8 commits)")

###  Code Quality

TestsPest

Code StyleLaravel Pint

### Embed Badge

![Health badge](/badges/maestrodimateo-simple-consul/health.svg)

```
[![Health](https://phpackages.com/badges/maestrodimateo-simple-consul/health.svg)](https://phpackages.com/packages/maestrodimateo-simple-consul)
```

###  Alternatives

[fumeapp/modeltyper

Generate TypeScript interfaces from Laravel Models

196277.9k](/packages/fumeapp-modeltyper)[slowlyo/owl-admin

基于 laravel、amis 开发的后台框架~

61214.2k26](/packages/slowlyo-owl-admin)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
