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

Configcat Client Laravel Package

configcat/configcat-client

ConfigCat PHP SDK client for feature flags and remote configuration. Fetch typed setting values from ConfigCat using your SDK key, with targeting by user attributes (region, email, custom). Supports PHP 8.1+ and integrates via Composer.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation

    composer require configcat/configcat-client
    

    Ensure your composer.json meets PHP 8.1+ requirements.

  2. Retrieve SDK Key Grab your SDK key from ConfigCat Dashboard.

  3. Initialize Client

    $client = new \ConfigCat\ConfigCatClient('YOUR_SDK_KEY');
    
  4. First Feature Flag Check

    $isFeatureEnabled = $client->getValue('feature_flag_key', false);
    if ($isFeatureEnabled) {
        // New logic
    }
    

Where to Look First

  • Laravel Sample App – Pre-configured Laravel integration.
  • ConfigCat Docs – Advanced use cases (targeting, caching, hooks).
  • ConfigCatClient Class – Core methods (getValue(), getAllValues(), forceRefresh()).

Implementation Patterns

Core Workflows

1. Basic Feature Flagging

// In a controller/service
public function toggleFeature(Request $request) {
    $client = app(ConfigCatClient::class);
    $isEnabled = $client->getValue('new_ui_enabled', false);

    return $isEnabled ? view('new-ui') : view('old-ui');
}

2. User-Specific Targeting

// Create a user object (mandatory: identifier)
$user = new \ConfigCat\User($request->user()->id, [
    'email' => $request->user()->email,
    'country' => $request->ip()->country(),
]);

// Fetch flag with targeting
$isBetaFeature = $client->getValue('beta_feature', false, $user);

3. Caching Strategies

// Configure cache (e.g., Redis)
$client = new \ConfigCat\ConfigCatClient('SDK_KEY', [
    \ConfigCat\ClientOptions::CACHE => new \ConfigCat\Cache\RedisCache(
        new \Redis(),
        'configcat'
    ),
    \ConfigCat\ClientOptions::POLLING_INTERVAL => 60, // Refresh every 60s
]);

4. Hooks for Observability

// Subscribe to config changes
$client->hooks()->onConfigChanged(function ($flags) {
    \Log::info('ConfigCat flags updated', ['flags' => $flags]);
});

// Handle evaluation details
$client->hooks()->onFlagEvaluated(function ($details) {
    \Log::debug('Flag evaluated', [
        'key' => $details->getKey(),
        'value' => $details->getValue(),
        'reason' => $details->getReason(),
    ]);
});

5. Offline Mode

// Force offline (cache-only)
$client->setOffline();

// Re-enable online mode
$client->setOnline();

6. Bulk Flag Evaluation

// Get all flag values at once
$allFlags = $client->getAllValues($user);
$isFeatureA = $allFlags['feature_a'] ?? false;

Laravel-Specific Patterns

Service Provider Binding

// In AppServiceProvider@boot()
$this->app->singleton(ConfigCatClient::class, function ($app) {
    return new \ConfigCat\ConfigCatClient(config('configcat.sdk_key'), [
        \ConfigCat\ClientOptions::CACHE => new \ConfigCat\Cache\ArrayCache(),
    ]);
});

Config File Integration

// config/configcat.php
return [
    'sdk_key' => env('CONFIGCAT_SDK_KEY'),
    'polling_interval' => env('CONFIGCAT_POLLING_INTERVAL', 60),
    'cache' => env('CONFIGCAT_CACHE', 'array'), // 'array', 'redis', etc.
];

Middleware for Feature Gating

// app/Http/Middleware/FeatureGate.php
public function handle($request, Closure $next) {
    $client = app(ConfigCatClient::class);
    if (!$client->getValue('api_v2_enabled', false)) {
        abort(503, 'API v2 is disabled.');
    }
    return $next($request);
}

Gotchas and Tips

Pitfalls

  1. Cache Invalidation Delays

    • Flags updated in the ConfigCat dashboard may take up to POLLING_INTERVAL seconds to propagate.
    • Fix: Use forceRefresh() to manually trigger a sync:
      $client->forceRefresh();
      
  2. User Object Requirements

    • The User object must have a unique identifier. Missing or duplicate IDs break targeting.
    • Tip: Use User::create($id, ['custom' => 'attributes']) for clarity.
  3. Offline Mode Pitfalls

    • In offline mode, the SDK only uses cached values. Ensure your cache is populated before going offline.
    • Debug: Check getLastFetchTime() to verify cache freshness.
  4. Logging Overhead

    • Default logging is minimal (WARNING level). Enable DEBUG only for troubleshooting:
      $client = new \ConfigCat\ConfigCatClient('SDK_KEY', [
          \ConfigCat\ClientOptions::LOG_LEVEL => \ConfigCat\Log\LogLevel::DEBUG,
      ]);
      
  5. Guzzle Deprecation

    • Direct Guzzle options (e.g., REQUEST_OPTIONS) are deprecated. Use FetchClientInterface for custom HTTP clients:
      $client = new \ConfigCat\ConfigCatClient('SDK_KEY', [
          \ConfigCat\ClientOptions::FETCH_CLIENT => \ConfigCat\Http\GuzzleFetchClient::create([
              \GuzzleHttp\RequestOptions::TIMEOUT => 5,
          ]),
      ]);
      

Debugging Tips

  1. Evaluation Details Use getValueDetails() to debug why a flag returned a specific value:

    $details = $client->getValueDetails('flag_key', false, $user);
    \Log::debug('Evaluation reason:', [
        'reason' => $details->getReason(),
        'matched_rule' => $details->getMatchedTargetingRule(),
    ]);
    
  2. Cache Inspection Check cached flags with:

    $client->getAllKeys(); // List all cached flag keys
    $client->getLastFetchTime(); // Unix timestamp of last fetch
    
  3. Network Issues

    • Enable DEBUG logging to catch HTTP errors.
    • Test connectivity with:
      try {
          $client->forceRefresh();
      } catch (\Exception $e) {
          \Log::error('ConfigCat refresh failed', ['error' => $e->getMessage()]);
      }
      

Extension Points

  1. Custom Cache Backends Implement \ConfigCat\Cache\CacheInterface for Redis, DynamoDB, etc.:

    class RedisCache implements \ConfigCat\Cache\CacheInterface {
        public function get(string $key): ?string { /* ... */ }
        public function set(string $key, string $value): void { /* ... */ }
        public function delete(string $key): void { /* ... */ }
    }
    
  2. Custom HTTP Clients Replace Guzzle with Psr-18 compliant clients (e.g., Symfony HTTP Client):

    use Symfony\Contracts\HttpClient\HttpClientInterface;
    
    class SymfonyFetchClient implements \ConfigCat\Http\FetchClientInterface {
        public function __construct(private HttpClientInterface $client) {}
        public function getClient(): \Psr\Http\Client\ClientInterface {
            return new class($this->client) implements \Psr\Http\Client\ClientInterface {
                // Adapt Symfony client to Psr-18
            };
        }
        public function createRequest(string $method, string $uri): \Psr\Http\Message\RequestInterface {
            // Adapt Symfony request to Psr-7
        }
    }
    
  3. Flag Overrides Override flags locally (e.g., for testing):

    $client = new \ConfigCat\ConfigCatClient('SDK_KEY', [
        \ConfigCat\ClientOptions::FLAG_OVERRIDES => [
            'debug_mode' => true, // Override 'debug_mode' flag
        ],
    ]);
    

Performance Tips

  1. Bulk Evaluation Use getAllValues() instead of multiple getValue() calls to reduce network overhead.

  2. Cache Tuning

    • Set POLLING_INTERVAL to balance freshness vs. load (e.g., 60 seconds for most apps).
    • For high-traffic apps, use a distributed cache (Redis) to avoid cache stampedes.
  3. Offline Mode Enable offline mode during deployments to avoid race conditions:

    if (app()->environment('deploying')) {
        $client->setOffline();
    }
    
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
terminal42/code-quality-tools
codifyo/ts-generator-bundle
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