PHPackages                             togglebox/sdk - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Utility &amp; Helpers](/categories/utility)
4. /
5. togglebox/sdk

ActiveLibrary[Utility &amp; Helpers](/categories/utility)

togglebox/sdk
=============

PHP SDK for ToggleBox - Remote Config, Feature Flags, and A/B Experiments

00PHP

Since Jan 30Pushed 3mo agoCompare

[ Source](https://github.com/ulpi-io/togglebox-php)[ Packagist](https://packagist.org/packages/togglebox/sdk)[ RSS](/packages/togglebox-sdk/feed)WikiDiscussions main Synced 1mo ago

READMEChangelogDependenciesVersions (1)Used By (0)

ToggleBox PHP SDK
=================

[](#togglebox-php-sdk)

Official PHP SDK for [ToggleBox](https://github.com/ulpi-io/togglebox) - Remote Config, Feature Flags, and A/B Experiments.

Installation
------------

[](#installation)

```
composer require togglebox/sdk
```

Quick Start
-----------

[](#quick-start)

```
use ToggleBox\ToggleBoxClient;
use ToggleBox\Types\ClientOptions;
use ToggleBox\Types\FlagContext;
use ToggleBox\Types\ExperimentContext;

// Initialize the client
$client = new ToggleBoxClient(new ClientOptions(
    platform: 'web',
    environment: 'production',
    apiUrl: 'https://api.yourdomain.com', // Self-hosted
    // OR for cloud:
    // tenantSubdomain: 'your-tenant',
    apiKey: 'your-api-key', // Optional for self-hosted
));
```

Tier 1: Remote Configs
----------------------

[](#tier-1-remote-configs)

Remote configs provide the same value to everyone - perfect for feature toggles, API URLs, and app settings.

```
// Get a single config value with type-safe default
$apiUrl = $client->getConfigValue('api_url', 'https://default.api.com');
$maxRetries = $client->getConfigValue('max_retries', 3);

// Get all active config parameters as key-value array
$allConfigs = $client->getAllConfigs();
// Returns: ['api_url' => 'https://...', 'max_retries' => 5, ...]
```

Tier 2: Feature Flags (2-Value Model)
-------------------------------------

[](#tier-2-feature-flags-2-value-model)

Feature flags support targeting by country and language with a simple 2-value model (A/B).

```
$context = new FlagContext(
    userId: 'user-123',
    country: 'US',
    language: 'en',
);

// Get flag result with full details
$result = $client->getFlag('new-checkout-ui', $context);
echo $result->value;       // The actual value (valueA or valueB)
echo $result->servedValue; // 'A' or 'B'
echo $result->reason;      // 'targeting_match', 'rollout', etc.

// Simple boolean check
if ($client->isFlagEnabled('dark-mode', $context)) {
    enableDarkMode();
}

// Get flag metadata without evaluation
$flagInfo = $client->getFlagInfo('dark-mode');
if ($flagInfo !== null) {
    echo $flagInfo->flagKey;     // 'dark-mode'
    echo $flagInfo->name;        // 'Dark Mode'
    echo $flagInfo->enabled;     // true/false
    echo $flagInfo->valueA;      // Value A
    echo $flagInfo->valueB;      // Value B
}
```

Tier 3: A/B Experiments
-----------------------

[](#tier-3-ab-experiments)

Full multi-variant experiments with traffic allocation and conversion tracking.

```
$context = new ExperimentContext(
    userId: 'user-123',
    country: 'US',
    language: 'en',
);

// Get the user's assigned variation
$variant = $client->getVariant('checkout-redesign', $context);

if ($variant !== null) {
    echo $variant->variationKey;  // 'control', 'variant_1', etc.
    echo $variant->variationName; // 'Control', 'Variant 1', etc.
    echo $variant->value;         // The variation's value (JSON or string)
    echo $variant->isControl;     // true/false
}

// Track a conversion
use ToggleBox\Types\ConversionData;

$client->trackConversion('checkout-redesign', $context, new ConversionData(
    metricName: 'purchase',
    value: 99.99, // Optional: for sum/average metrics
));

// Get experiment metadata without assignment
$experimentInfo = $client->getExperimentInfo('checkout-redesign');
if ($experimentInfo !== null) {
    echo $experimentInfo->experimentKey; // 'checkout-redesign'
    echo $experimentInfo->name;          // 'Checkout Redesign'
    echo $experimentInfo->status;        // 'running', 'draft', 'completed'
    print_r($experimentInfo->variations); // Array of variations
}

// Flush stats to server (call at end of request)
$client->flushStats();
```

Caching
-------

[](#caching)

By default, the SDK uses an in-memory array cache that persists for the lifetime of the request. For better performance across requests, provide a PSR-16 compatible cache:

```
use ToggleBox\Cache\PsrCacheAdapter;

// Using Symfony Cache
$symfonyCache = new \Symfony\Component\Cache\Psr16Cache(
    new \Symfony\Component\Cache\Adapter\RedisAdapter($redis)
);

$client = new ToggleBoxClient(
    new ClientOptions(
        platform: 'web',
        environment: 'production',
        apiUrl: 'https://api.yourdomain.com',
        cache: new CacheOptions(
            enabled: true,
            ttl: 300, // 5 minutes
        ),
    ),
    new PsrCacheAdapter($symfonyCache),
);
```

Manual Cache Refresh
--------------------

[](#manual-cache-refresh)

```
// Force refresh all cached data
$client->refresh();

// Clear all caches
$client->clearCache();
```

Health Check
------------

[](#health-check)

```
// Check API connectivity
try {
    $health = $client->checkConnection();
    echo $health['status']; // 'ok'
} catch (\ToggleBox\Exceptions\ToggleBoxException $e) {
    // API is unreachable
    log_error('ToggleBox API is down: ' . $e->getMessage());
}
```

Error Handling
--------------

[](#error-handling)

```
use ToggleBox\Exceptions\ToggleBoxException;
use ToggleBox\Exceptions\NetworkException;
use ToggleBox\Exceptions\ConfigurationException;

try {
    $variant = $client->getVariant('my-experiment', $context);
} catch (NetworkException $e) {
    // API request failed
    log_error('ToggleBox API error: ' . $e->getMessage());
} catch (ToggleBoxException $e) {
    // Other SDK errors (e.g., experiment not found)
    log_error('ToggleBox error: ' . $e->getMessage());
}
```

Configuration Options
---------------------

[](#configuration-options)

OptionTypeRequiredDescription`platform`stringYesPlatform name (e.g., 'web', 'mobile')`environment`stringYesEnvironment name (e.g., 'production', 'staging')`apiUrl`string\*API base URL (for self-hosted)`tenantSubdomain`string\*Tenant subdomain (for cloud)`apiKey`stringNoAPI key for authentication`cache`CacheOptionsNoCache configuration`configVersion`stringNoDefault config version ('stable', 'latest', or specific)\* Either `apiUrl` or `tenantSubdomain` is required, but not both.

Requirements
------------

[](#requirements)

- PHP 8.1 or higher
- Guzzle HTTP client

License
-------

[](#license)

MIT

###  Health Score

18

—

LowBetter than 8% of packages

Maintenance53

Moderate activity, may be stable

Popularity0

Limited adoption so far

Community6

Small or concentrated contributor base

Maturity12

Early-stage or recently created project

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

### Community

Maintainers

![](https://www.gravatar.com/avatar/20f19ea84963f3f5874cb28d5681684402f313ab70683faa1f1962a6fbcf0863?d=identicon)[CiprianSpiridon](/maintainers/CiprianSpiridon)

---

Top Contributors

[![CiprianSpiridon](https://avatars.githubusercontent.com/u/1598171?v=4)](https://github.com/CiprianSpiridon "CiprianSpiridon (12 commits)")

### Embed Badge

![Health badge](/badges/togglebox-sdk/health.svg)

```
[![Health](https://phpackages.com/badges/togglebox-sdk/health.svg)](https://phpackages.com/packages/togglebox-sdk)
```

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
