toggly/feature-management-php

Toggly Feature Management library for PHP with Laravel and WordPress support

Maintainers

Package info

github.com/ops-ai/Toggly.FeatureManagement.PHP

Documentation

pkg:composer/toggly/feature-management-php

Transparency log

Statistics

Installs: 0

Dependents: 0

Suggesters: 0

Stars: 0

Open Issues: 0

dev-main 2026-07-12 23:59 UTC

This package is auto-updated.

Last update: 2026-07-13 00:00:27 UTC


README

Packagist License: MIT Documentation Website

Official PHP SDK for Toggly feature flags — Composer package with native Laravel and WordPress support.

Features

  • Full Feature Parity: Matches the functionality of the .NET Toggly.FeatureManagement library
  • Signed Definitions: ECDSA signature verification for secure feature definitions
  • Real-time Updates: WebSocket support for instant feature updates (with polling fallback)
  • Usage Statistics: Automatic tracking of feature usage and user analytics
  • Metrics Collection: Support for measurements, observations, and counters
  • Snapshot Providers: Cache, database, and file-based snapshot storage
  • Laravel Integration: Native Laravel service provider, facade, and middleware
  • WordPress Plugin: Full WordPress plugin with admin interface and hooks
  • PSR Standards: Built on PSR-4, PSR-11, PSR-16, PSR-18, and PSR-17

Installation

Composer

composer require toggly/feature-management-php

Quick Start

Laravel

  1. Register the service provider in config/app.php:
'providers' => [
    // ...
    Toggly\Laravel\ServiceProvider::class,
],
  1. Publish the configuration:
php artisan vendor:publish --tag=toggly-config
  1. Configure in .env:
TOGGLY_APP_KEY=your-app-key
TOGGLY_ENVIRONMENT=Production
TOGGLY_USE_SIGNED_DEFINITIONS=false
  1. Use in your code:
use Toggly\Laravel\Facades\Toggly;

// Check if feature is enabled
if (Toggly::isEnabled('new-checkout')) {
    return view('checkout.v2');
}

// With context
$enabled = Toggly::isEnabledFor('premium-feature', [
    'userId' => $user->id,
    'plan' => $user->plan
]);

// State change handler
Toggly::whenFeatureTurnsOn('new-api', function() {
    // Initialize new API
});

// Record usage
Toggly::recordUsage('feature-key');

// Record metrics
Toggly::measure('checkout-completed', 125.50);
Toggly::observe('active-users', 1500);
Toggly::incrementCounter('api-calls', 1);
  1. Use middleware in routes:
Route::get('/new-feature', function () {
    return view('new-feature');
})->middleware('feature:new-feature');

WordPress

  1. Install the plugin by copying to wp-content/plugins/toggly/

  2. Activate the plugin in WordPress admin

  3. Configure in Settings > Toggly:

    • App Key
    • Environment
    • Base URL (optional)
    • Use Signed Definitions (optional)
  4. Use in templates:

<?php if (toggly_is_enabled('new-header')): ?>
    <?php get_template_part('header', 'new'); ?>
<?php endif; ?>
  1. Use shortcode:
[toggly_feature name="premium-content"]
    <!-- Premium content here -->
[/toggly_feature]
  1. Use hooks in functions.php:
add_action('toggly_feature_turns_on', function($featureKey) {
    if ($featureKey === 'new-theme') {
        // Activate new theme
    }
});

Core Library Usage

Basic Usage

use Toggly\FeatureManagement\Config\TogglySettings;
use Toggly\FeatureManagement\Core\FeatureProvider;
use Toggly\FeatureManagement\Core\FeatureManager;
use Toggly\FeatureManagement\Http\TogglyHttpClient;

$settings = new TogglySettings([
    'app_key' => 'your-app-key',
    'environment' => 'Production',
]);

$httpClient = new TogglyHttpClient(/* PSR-18 client */, /* PSR-17 factory */, $settings->getBaseUrl());
$featureProvider = new FeatureProvider($settings, $httpClient, /* state service */);
$featureManager = new FeatureManager($featureProvider, /* usage stats */, /* secure provider */);

// Check feature
if ($featureManager->isEnabled('my-feature')) {
    // Feature is enabled
}

Snapshot Providers

Cache Provider (PSR-16)

use Toggly\FeatureManagement\Storage\SnapshotProviders\CacheSnapshotProvider;
use Toggly\FeatureManagement\Storage\SnapshotSettings;

$snapshotProvider = new CacheSnapshotProvider(
    $cache, // PSR-16 cache implementation
    new SnapshotSettings(['document_name' => 'toggly_features']),
    86400 // TTL in seconds
);

Database Provider (PDO)

use Toggly\FeatureManagement\Storage\SnapshotProviders\DatabaseSnapshotProvider;

$snapshotProvider = new DatabaseSnapshotProvider(
    $pdo, // PDO instance
    new SnapshotSettings(['document_name' => 'toggly_features'])
);

File Provider

use Toggly\FeatureManagement\Storage\SnapshotProviders\FileSnapshotProvider;

$snapshotProvider = new FileSnapshotProvider(
    '/path/to/snapshots',
    new SnapshotSettings(['document_name' => 'toggly_features.json'])
);

Configuration

TogglySettings

$settings = new TogglySettings([
    'app_key' => 'your-app-key',
    'environment' => 'Production',
    'base_url' => 'https://app.toggly.io/',
    'use_signed_definitions' => true,
    'allowed_key_ids' => ['key-id-1', 'key-id-2'],
    'refresh_interval' => 300, // 5 minutes
    'app_version' => '1.0.0',
    'instance_name' => 'server-1',
    'undefined_enabled_on_development' => false,
]);

Advanced Features

Feature State Change Handlers

$stateService = $container->get(FeatureStateServiceInterface::class);

// Register callback
$id = $stateService->whenFeatureTurnsOn('new-feature', function() {
    // Initialize feature
});

// Unregister
$stateService->unregisterFeatureStateChange('new-feature', $id);

Custom Metrics

$metricsService = $container->get(MetricsServiceInterface::class);

// Record measurement (aggregated over time)
$metricsService->measure('revenue', 1250.50);

// Record observation (point-in-time)
$metricsService->observe('active-users', 1500);

// Increment counter
$metricsService->incrementCounter('api-calls', 1);

Custom Context Provider

class MyContextProvider implements FeatureContextProviderInterface
{
    public function getContextIdentifier(): ?string
    {
        // Return unique user identifier
        return $this->getCurrentUserId();
    }

    // ... implement other methods
}

Requirements

  • PHP 7.4 or higher (8.1+ recommended)
  • PSR-18 HTTP client (e.g., Guzzle, Symfony HTTP Client)
  • PSR-16 cache (optional, for snapshot provider)
  • PSR-11 container (optional, for dependency injection)

Laravel Requirements

  • Laravel 8.0 or higher
  • illuminate/support
  • illuminate/http

WordPress Requirements

  • WordPress 5.0 or higher
  • No external dependencies (uses WordPress APIs)

Architecture

The library follows a modular architecture:

  • Core Library: Framework-agnostic core functionality
  • Laravel Integration: Service provider, facade, middleware, and filters
  • WordPress Plugin: Full plugin with admin interface

Core Components

  • FeatureProvider: Fetches and manages feature definitions
  • FeatureManager: Evaluates features with stats tracking
  • FeatureStateService: Manages state change notifications
  • UsageStatsProvider: Collects and sends usage statistics
  • MetricsService: Collects custom metrics for experiments
  • EcdsaSignatureVerifier: Verifies signed definitions
  • JwkManager: Manages JSON Web Keys for signature verification

Snapshot Providers

Three snapshot provider implementations are available:

  1. CacheSnapshotProvider: Uses PSR-16 cache (Redis, Memcached, etc.)
  2. DatabaseSnapshotProvider: Uses PDO (MySQL, PostgreSQL, SQLite)
  3. FileSnapshotProvider: Uses file system storage

Development

Running Tests

composer test

Code Style

The project follows PSR-12 coding standards.

Contributing

Please open an issue first for bugs and feature ideas, then follow CONTRIBUTING.md. Large PRs without prior discussion may be closed.

Security

Report vulnerabilities privately via GitHub Private Vulnerability Reporting. See SECURITY.md. Do not file public issues for security reports.

License

MIT

Support