Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Php Consul Api Laravel Package

dcarbone/php-consul-api

PHP client for the Consul HTTP API. Built for Composer and modeled after HashiCorp’s Go client, with version compatibility guidance and flexible configuration (defaults from Consul env vars or custom config with Guzzle, address, scheme, datacenter, auth, tokens).

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require dcarbone/php-consul-api
    

    Register the service provider in config/app.php:

    'providers' => [
        DCarbone\ConsulApi\ConsulServiceProvider::class,
    ],
    
  2. Basic Configuration Add Consul server URL to .env:

    CONSUL_HOST=http://localhost:8500
    

    Publish config (optional):

    php artisan vendor:publish --provider="DCarbone\ConsulApi\ConsulServiceProvider"
    
  3. First Use Case: Health Check

    use DCarbone\ConsulApi\Consul;
    
    $consul = app(Consul::class);
    $checks = $consul->get('/v1/agent/self')['Checks'];
    

Implementation Patterns

Common Workflows

  1. Service Discovery

    // Register a service
    $consul->post('/v1/agent/service/register', [
        'ID'      => 'my-service',
        'Name'    => 'My Service',
        'Address' => '127.0.0.1',
        'Port'    => 8080,
        'Check'   => [
            'HTTP' => 'http://127.0.0.1:8080/health',
            'Interval' => '10s',
        ],
    ]);
    
    // Query services
    $services = $consul->get('/v1/catalog/service/my-service');
    
  2. Key-Value Store

    // Set/get a key
    $consul->put('/v1/kv/my-app/config', json_encode(['debug' => true]));
    $config = json_decode($consul->get('/v1/kv/my-app/config')[0]['Value'], true);
    
  3. Event-Driven Patterns

    // Watch for changes (e.g., service updates)
    $consul->watch('/v1/catalog/service/my-service', function ($data) {
        // Handle service changes (e.g., trigger cache refresh)
    }, 5); // Check every 5 seconds
    

Integration Tips

  • Laravel Service Container: Bind custom Consul clients per environment:
    $this->app->bind('consul', function ($app) {
        return new Consul($app['config']['consul.custom_host']);
    });
    
  • Queue Jobs: Offload long-running Consul operations (e.g., bulk service registration) to queues.
  • Caching: Cache frequent queries (e.g., service lists) with Laravel’s cache driver:
    $services = Cache::remember('consul-services', now()->addMinutes(1), function () {
        return $consul->get('/v1/catalog/service/my-service');
    });
    

Gotchas and Tips

Pitfalls

  1. Rate Limiting

    • Consul enforces rate limits. Handle 429 Too Many Requests by:
      • Implementing exponential backoff in retries.
      • Using the retry option in the client:
        $consul->get('/v1/health/service/my-service', ['retry' => 3]);
        
  2. ACL Tokens

    • If using ACLs, ensure the token is passed in headers:
      $consul->setToken('my-acl-token');
      
    • Debugging: Check for 403 Forbidden errors if ACLs are misconfigured.
  3. Connection Timeouts

    • Default timeout is 5 seconds. Adjust in config:
      'timeout' => 10, // seconds
      
  4. Watch Indexes

    • The watch method requires a valid Index from the initial response. Always fetch the latest index first:
      $initial = $consul->get('/v1/kv/my-key');
      $consul->watch('/v1/kv/my-key', $initial['Index'], ...);
      

Debugging

  • Enable Debug Mode:
    $consul->setDebug(true); // Logs raw requests/responses
    
  • Common Errors:
    • 404 Not Found: Verify the endpoint (e.g., /v1/agent/check/register vs /v1/agent/service/register).
    • 500 Internal Server Error: Check Consul server logs for malformed requests.

Extension Points

  1. Custom Middleware Add middleware to modify requests/responses:

    $consul->addMiddleware(function ($request) {
        $request->headers->set('X-Custom-Header', 'value');
    });
    
  2. Event Listeners Extend the Consul class to add custom methods:

    class ExtendedConsul extends Consul {
        public function registerServiceWithRetry($service, $retries = 3) {
            for ($i = 0; $i < $retries; $i++) {
                try {
                    return parent::post('/v1/agent/service/register', $service);
                } catch (\Exception $e) {
                    if ($i === $retries - 1) throw $e;
                    sleep(1);
                }
            }
        }
    }
    
  3. Testing Use the MockHandler from Guzzle for unit tests:

    use GuzzleHttp\Handler\MockHandler;
    use GuzzleHttp\Psr7\Response;
    
    $mock = new MockHandler([
        new Response(200, [], json_encode(['Checks' => []])),
    ]);
    $consul = new Consul(new Client(['handler' => $mock]));
    
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
codifyo/ts-generator-bundle
andydefer/laravel-cluster
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky
spatie/mailcoach-vapor