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

Consul Php Sdk Laravel Package

friendsofphp/consul-php-sdk

PHP SDK for HashiCorp Consul by FriendsOfPHP. Provides a clean API client to interact with Consul’s HTTP endpoints—service discovery, KV store, health checks, sessions, ACL, and agent/catalog operations—usable in any PHP app or framework.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require friendsofphp/consul-php-sdk
    

    Verify the package loads in config/consul.php (auto-generated by the package).

  2. First Use Case: Service Discovery

    use FriendsOfPHP\Consul\Consul;
    
    $consul = new Consul('http://consul-server:8500');
    $services = $consul->getService('web')->get();
    
    • Check the official docs for API endpoints.
    • Use getAgent() for local node info (e.g., getAgent()->getSelf()).
  3. Configuration:

    • Override defaults in config/consul.php:
      'servers' => [
          'default' => [
              'host' => env('CONSUL_HOST', 'localhost'),
              'port' => env('CONSUL_PORT', 8500),
              'scheme' => 'http',
          ],
      ],
      
    • Use the ConsulFactory for dependency injection:
      $consul = app('consul');
      

Implementation Patterns

Common Workflows

1. Service Registration & Health Checks

  • Register a service:
    $consul->getService('api')->setChecks([
        new \FriendsOfPHP\Consul\Checks\ServiceCheck(
            'API HTTP Check',
            'http',
            '/health',
            5,
            '10s'
        )
    ])->save();
    
  • Deregister on shutdown (e.g., in AppServiceProvider boot):
    register_shutdown_function(function () {
        app('consul')->getService('api')->delete();
    });
    

2. Key-Value Store

  • Store/retrieve config:
    $consul->getKv()->set('app/config', json_encode(['debug' => true]));
    $config = json_decode($consul->getKv()->get('app/config')->getValue(), true);
    

3. Dynamic Configuration with Events

  • Listen for KV changes (e.g., reload config):
    $consul->getKv()->watch('app/config', function ($event) {
        $this->reloadConfig($event->getValue());
    });
    

4. Leader Election

  • Claim leadership:
    $session = $consul->getSession()->create('worker-leader', '10s');
    $leader = $consul->getSession()->getLeader('worker-leader');
    

5. Integration with Laravel Services

  • Cache Consul data (e.g., service list):
    Cache::remember('consul-services', now()->addHour(), function () {
        return app('consul')->getAgent()->getServices();
    });
    

Integration Tips

Laravel Service Provider

Extend the package with a provider:

class ConsulServiceProvider extends ServiceProvider
{
    public function register()
    {
        $this->app->singleton('consul', function () {
            return new Consul(config('consul.servers.default'));
        });
    }

    public function boot()
    {
        $this->publishes([
            __DIR__.'/config/consul.php' => config_path('consul.php'),
        ], 'consul-config');
    }
}

API Routes

Expose Consul data via Laravel routes:

Route::get('/services', function () {
    return response()->json(app('consul')->getAgent()->getServices());
});

Testing

Mock Consul in tests:

$mockConsul = Mockery::mock('overload:consul');
$mockConsul->shouldReceive('getService')->andReturnSelf();
$mockConsul->shouldReceive('get')->andReturn(['web' => ['ServiceAddress' => '127.0.0.1']]);

Gotchas and Tips

Pitfalls

  1. Connection Timeouts:

    • Default timeout is 5s. Increase for slow networks:
      $consul = new Consul('http://consul-server:8500', [
          'timeout' => 30,
      ]);
      
  2. ACL Token Management:

    • If using ACLs, pass the token explicitly:
      $consul = new Consul('http://consul-server:8500', [
          'token' => env('CONSUL_ACL_TOKEN'),
      ]);
      
    • Gotcha: Missing tokens cause silent failures (check HTTP status codes).
  3. Race Conditions in Sessions:

    • Sessions expire quickly. Use renew() in long-running processes:
      $session = $consul->getSession()->create('lock', '30s');
      while (true) {
          try {
              $session->renew();
              break;
          } catch (\FriendsOfPHP\Consul\Exception\ConsulException $e) {
              sleep(1);
          }
      }
      
  4. KV Watching:

    • Watches are not persistent. Re-establish on app restart.
    • Use setIndex() to resume from a known state:
      $consul->getKv()->watch('app/config', $callback, $index);
      
  5. Service Deregistration:

    • Gotcha: Forgetting to deregister can leak services. Use a finally block or Laravel’s terminating event:
      app()->terminating(function () {
          app('consul')->getService('api')->delete();
      });
      

Debugging

  1. Enable HTTP Logging:

    $consul = new Consul('http://consul-server:8500', [
        'http_client' => new \GuzzleHttp\Client([
            'debug' => fopen('consul.log', 'w'),
        ]),
    ]);
    
  2. Check HTTP Status Codes:

    • Wrap calls in try-catch to inspect ConsulException:
      try {
          $consul->getService('nonexistent')->get();
      } catch (\FriendsOfPHP\Consul\Exception\ConsulException $e) {
          \Log::error($e->getResponse()->getStatusCode());
      }
      
  3. Validate Consul Server Health:

    • Test connectivity first:
      $response = $consul->getAgent()->getSelf();
      if (!$response->getStatus()) {
          throw new \RuntimeException('Consul server unreachable');
      }
      

Extension Points

  1. Custom HTTP Client:

    • Replace Guzzle with your own client (e.g., for retries):
      $client = new \GuzzleHttp\Client(['timeout' => 10]);
      $consul = new Consul('http://consul-server:8500', ['http_client' => $client]);
      
  2. Event Dispatching:

    • Extend the SDK to dispatch Laravel events:
      $consul->getKv()->watch('app/config', function ($event) {
          event(new ConfigUpdated($event->getValue()));
      });
      
  3. Retry Logic:

    • Implement exponential backoff for transient failures:
      $attempts = 0;
      while ($attempts < 3) {
          try {
              $consul->getService('api')->get();
              break;
          } catch (\Exception $e) {
              $attempts++;
              sleep(2 ** $attempts);
          }
      }
      
  4. Local Development:

    • Use docker-compose with Consul:
      services:
        consul:
          image: consul:latest
          ports:
            - "8500:8500"
      
    • Point Laravel to http://localhost:8500.
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.
besmartand-pro/php-quality-config
sentix/ai-chatbot
codifyo/ts-generator-bundle
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