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

Openfeature Provider Laravel Package

configcat/openfeature-provider

OpenFeature provider for PHP that connects the OpenFeature PHP SDK to ConfigCat. Configure with your ConfigCat SDK key and optional client options, then evaluate feature flags via the OpenFeature client (boolean, string, etc.). PHP 8.1+.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Install the Package

    composer require configcat/openfeature-provider
    

    Ensure your project meets the PHP 8.1+ requirement.

  2. Initialize OpenFeature

    use OpenFeature\Api\OpenFeatureAPI;
    use ConfigCat\OpenFeature\ConfigCatProvider;
    
    $api = OpenFeatureAPI::getInstance();
    $api->setProvider(new ConfigCatProvider('YOUR_SDK_KEY'));
    
  3. First Feature Flag Evaluation

    $client = $api->getClient();
    $isFeatureEnabled = $client->getBooleanValue('my_flag_key', false);
    

Where to Look First

  • ConfigCat PHP SDK Docs for flag evaluation syntax, user targeting, and caching.
  • OpenFeature PHP SDK for provider-agnostic API patterns (e.g., getStringValue, getIntegerValue).
  • ConfigCat Dashboard to define flags and test configurations in real-time.

Implementation Patterns

Core Workflow: Feature Flag Integration

  1. Provider Initialization

    $api->setProvider(new ConfigCatProvider(
        sdkKey: 'YOUR_KEY',
        options: [
            ClientOptions::LOG_LEVEL => LogLevel::ERROR, // Reduce noise in production
            ClientOptions::CACHE_REFRESH_INTERVAL => 60, // Sync flags every minute
        ]
    ));
    
    • Tip: Use LogLevel::ERROR in production to avoid logging sensitive flag evaluations.
  2. Flag Evaluation in Controllers/Services

    public function showDashboard(Request $request) {
        $client = OpenFeatureAPI::getInstance()->getClient();
        $user = $request->user();
    
        // Target flags to specific users/groups
        $client->setTargetingContext([
            'userId' => $user->id,
            'email' => $user->email,
        ]);
    
        if ($client->getBooleanValue('new_dashboard_ui', false)) {
            return view('dashboard.new');
        }
        return view('dashboard.legacy');
    }
    
  3. Multi-Type Flags

    $timeout = $client->getIntegerValue('api_timeout_ms', 5000);
    $env = $client->getStringValue('app_environment', 'staging');
    

Advanced Patterns

  • Lazy Initialization

    // Cache the OpenFeature client in a service container (Laravel)
    $this->app->singleton(OpenFeatureClient::class, function ($app) {
        $api = OpenFeatureAPI::getInstance();
        $api->setProvider(new ConfigCatProvider(config('configcat.sdk_key')));
        return $api->getClient();
    });
    
  • Dynamic SDK Key (Multi-Tenant)

    $provider = new ConfigCatProvider(
        tenantSdkKey: $tenant->configcat_key,
        options: ['cacheRefreshInterval' => 30]
    );
    $api->setProvider($provider);
    
  • Fallback Logic

    $isEnabled = $client->getBooleanValue('experimental_feature', false);
    if (!$isEnabled) {
        // Fallback behavior
        Log::info('Feature disabled; using default workflow.');
    }
    

Integration Tips

  • Laravel Service Providers Bind the provider in AppServiceProvider:

    public function boot() {
        OpenFeatureAPI::getInstance()->setProvider(
            new ConfigCatProvider(config('configcat.sdk_key'))
        );
    }
    
  • Testing Use ConfigCat’s sandbox mode or mock the provider for unit tests:

    $mockProvider = $this->createMock(ConfigCatProvider::class);
    $mockProvider->method('getValue')->willReturn(true);
    OpenFeatureAPI::getInstance()->setProvider($mockProvider);
    

Gotchas and Tips

Common Pitfalls

  1. SDK Key Mismatch

    • Issue: Flags return null or default values unexpectedly.
    • Fix: Verify the SDK key in the ConfigCat Dashboard matches the one in your code.
    • Debug: Check LogLevel::DEBUG logs for connection errors.
  2. Caching Quirks

    • Issue: Flags update delayed due to cacheRefreshInterval.
    • Fix: Set a low interval (e.g., 5 seconds) during development, but increase it (e.g., 60) in production to reduce API calls.
    • Workaround: Use forceRefresh() (if supported by the underlying ConfigCat SDK) for critical flags:
      $client->getValue('critical_flag', false, true); // Force refresh
      
  3. Context Targeting

    • Issue: User-specific flags ignore targeting context.
    • Fix: Always set the context before evaluating flags:
      $client->setTargetingContext(['userId' => '123']);
      $isEnabled = $client->getBooleanValue('premium_feature', false);
      
  4. Provider Singleton

    • Issue: Multiple providers set on OpenFeatureAPI may cause conflicts.
    • Fix: Reuse the same provider instance or reset the API between tests:
      OpenFeatureAPI::getInstance()->reset();
      

Debugging Tips

  • Enable Debug Logging

    $options = [ClientOptions::LOG_LEVEL => LogLevel::DEBUG];
    $api->setProvider(new ConfigCatProvider('KEY', $options));
    
    • Check logs for:
      • SDK initialization errors.
      • Flag evaluation results (e.g., Flag 'flag_key' resolved to: true).
  • Validate Flag Keys

    • Typos in flag keys (e.g., new_ui vs. newUI) will return defaults. Use the ConfigCat Dashboard to verify keys.
  • Network Issues

    • If flags fail to load, ensure:
      • Your server can reach https://cdn.configcat.com.
      • No firewall/proxy blocks the request (test with LogLevel::DEBUG).

Extension Points

  1. Custom Providers

    • Extend ConfigCatProvider to add middleware for flag evaluations:
      class CustomConfigCatProvider extends ConfigCatProvider {
          public function getValue(string $flagKey, mixed $defaultValue): mixed {
              // Pre-process flag key or context
              return parent::getValue($flagKey, $defaultValue);
          }
      }
      
  2. Hybrid Providers

    • Combine with other OpenFeature providers (e.g., fallback to a local JSON config):
      $api->setProvider(new HybridProvider([
          new ConfigCatProvider('primary_key'),
          new JsonFileProvider('backup_flags.json'),
      ]));
      
  3. Event Listeners

    • Subscribe to ConfigCat’s SDK events (if supported) to log flag changes:
      ConfigCat::getInstance()->addEventListener(new class implements ConfigCatEventListener {
          public function onConfigurationChanged(ConfigCatConfigurationChangedEvent $event) {
              Log::info('Flags refreshed at: ' . $event->getTimestamp());
          }
      });
      

Configuration Quirks

  • Offline Mode

    • The ConfigCat SDK caches flags locally. To simulate offline behavior:
      $options = [
          ClientOptions::OFFLINE => true,
          ClientOptions::CACHE_REFRESH_INTERVAL => 0,
      ];
      
    • Note: Flags will use cached values even if the server is unreachable.
  • Environment Variables

    • Store the SDK key in .env:
      CONFIGCAT_SDK_KEY=your_key_here
      
    • Access it in Laravel:
      $api->setProvider(new ConfigCatProvider(config('configcat.sdk_key')));
      
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.
croct/coding-standard
croct/plug-php
nqxcode/phpmorphy
boundwize/pyrameter
testo/facade
develia/commons
dmstr/symfony-system-resources-bundle
cuci/prototurk-sdk
cuci/prototurk-sdk-symfony
renatomarinho/laravel-page-speed
develia/geo-bundle
austinheap/laravel-database-encryption
dreamzy/livewire-charts
touchestate-sdk/php-sdk
22h/doctrine-garbage-collection-bundle
imbo/imbo-coding-standard
visualbuilder/filament-lottie
servicioslineaonce/starter-kit
atomcoder/laravel-reorderable
irajul/filament-shadcn-theme