Server SDKs

PHP Server SDK

Evaluate configs and feature flags locally for any context with the PHP server SDK, which keeps the values it receives in a local store that the PHP processes of a host share

Introduction

The PHP Server SDK is a server-side SDK that evaluates configs and their targeting rules. It receives configs, targeting rules and segments from ConfigDirector services and evaluates configs locally for any context, so a read makes no network call.

A PHP request starts with empty memory, so unlike the other server SDKs, the PHP SDK holds no connection of its own. It keeps the values it receives in a local store, a folder on the host that its PHP processes share, and one request per polling interval asks ConfigDirector for new ones for the whole host. To have a change arrive in about a second instead, run the optional streaming process on each host. How the SDK connects explains both.

The minimum PHP version supported is 8.3, on a 64-bit PHP.

Installation

The SDK can be installed with Composer. Its package page is on Packagist: https://packagist.org/packages/configdirector/server-sdk

composer require configdirector/server-sdk

The SDK needs the curl and JSON extensions, and Composer refuses to install it on a 32-bit PHP. Run it on a PHP release with the fixes for CVE-2026-109618 and CVE-2026-109619: 8.3.36, 8.4.27, 8.5.12 or later. Composer also installs the SDK on an earlier 8.3, 8.4 or 8.5 release, which ConfigDirector does not test.

The pcntl extension, which the package suggests, lets the streaming process send its last telemetry when it is stopped.

The source code, the issues and the changelog are in the php-sdks repository, which also holds a Slim and a Laravel sample application.

Configure and initialize the client

  1. Create a client providing your server SDK key. You can retrieve a server SDK key for each environment under SDK keys in the dashboard's navigation panel.
  2. Call initialize() before your code reads values.
index.php
use ConfigDirector\ConfigDirector;

// IMPORTANT: Do not commit the server SDK key to your source code, it is a secret value.
// Creating the client makes no network call.
$client = ConfigDirector::createClient(serverSdkKey: 'YOUR-SERVER-SDK-KEY');

// Reads the values kept on this host. Only when there are none yet, as on the first
// request of a new host or container, does it ask ConfigDirector and wait up to the
// connection timeout. Without values, reads return their in-code default value.
$client->initialize();

Create one client per request, for example in your framework's container, and read through it as often as you need. The SDK disposes of the client when the request ends.

Server SDK keys are secret values. Do not commit them to your source code repository. Provide them at runtime via environment variables instead.

initialize() reads the values kept in the host's local store and makes the client ready. When the local store holds none yet, as on the first request of a new host or container, it asks ConfigDirector and waits up to the connection timeout, 3 seconds by default; requests that arrive meanwhile wait for that same answer. When it returns without values, the SDK logs why, and every read returns its in-code default value. initialize() does not throw for that: only in offline mode does it throw, for a file of values it cannot load. isReady() reports whether the client has values to serve.

In a framework

Create the client in your framework's container, so that each request gets a client of its own. In Laravel, bind it with scoped(), as the Laravel sample does:

app/Providers/ConfigDirectorServiceProvider.php
use App\ConfigDirectorSettings;
use ConfigDirector\ConfigDirector;
use ConfigDirector\ConfigDirectorClient;
use Illuminate\Config\Repository;
use Illuminate\Contracts\Foundation\Application;
use Illuminate\Log\LogManager;
use Illuminate\Support\ServiceProvider;

final class ConfigDirectorServiceProvider extends ServiceProvider
{
    #[\Override]
    public function register(): void
    {
        $this->app->singleton(
            ConfigDirectorSettings::class,
            static fn(Application $app): ConfigDirectorSettings => ConfigDirectorSettings::fromConfiguration(
                $app->make(Repository::class)->array('configdirector'),
            ),
        );

        $this->app->scoped(
            ConfigDirectorClient::class,
            static function (Application $app): ConfigDirectorClient {
                $settings = $app->make(ConfigDirectorSettings::class);
                $client = ConfigDirector::createClient(
                    serverSdkKey: $settings->serverSdkKey,
                    metadata: $settings->metadata,
                    connection: $settings->connection,
                    logger: $app->make(LogManager::class)->channel(ConfigDirectorSettings::LOG_CHANNEL),
                );
                $client->initialize();

                return $client;
            },
        );
    }
}

ConfigDirectorSettings is the sample's own settings class. It turns config/configdirector.php, which reads CONFIGDIRECTOR_SERVER_KEY, CONFIGDIRECTOR_STORAGE_PATH and the other settings from the environment, into the server SDK key, the metadata and the ConnectionOptions, so that the client and the streaming process command share one local store and one name in ConfigDirector.

Take the client as an argument of the method that handles the request, not of a controller's constructor:

app/Http/Controllers/CheckoutController.php
use ConfigDirector\ConfigDirectorClient;
use Illuminate\Http\JsonResponse;

final class CheckoutController
{
    public function __invoke(ConfigDirectorClient $client): JsonResponse
    {
        return new JsonResponse(['newCheckout' => $client->getValue('new-checkout', false)]);
    }
}

Laravel keeps one controller instance for its route, and Octane and queue workers keep the application in memory between requests and jobs. There, a client given to a constructor outlives the request it was made for and keeps serving the values it read first, while a scoped() binding gives each request and job a client that has read the local store. A singleton() binding would do the same harm as a constructor.

In Slim, define the client as a container entry, as the Slim sample does.

Additional configuration options

createClient takes named arguments, all optional. Only an offline client can leave out the server SDK key. createClient throws ConfigDirectorValidationException for a setting it cannot use, such as a missing key, a relative storagePath, or a URL with a query, rather than returning a client that quietly never updates.

metadata

The metadata argument allows you to provide your application's name and version. These values can be used in targeting rules conditionals. For example, if a certain feature should only be enabled starting with a certain version of your application.

index.php
use ConfigDirector\Metadata;

$client = ConfigDirector::createClient(
    serverSdkKey: 'YOUR-SERVER-SDK-KEY',
    metadata: new Metadata(appName: 'YOUR-APP-NAME', appVersion: '1.0.2'),
);

logger and logLevel

The SDK logs through a PSR-3 logger. Pass one as logger, such as a Monolog logger or a channel of your framework's log, to send the SDK's lines there.

Without a logger, the SDK writes warnings and errors through PHP's error_log. logLevel takes a PSR-3 level to write more or less, and has no effect when you pass a logger:

index.php
use Psr\Log\LogLevel;

$client = ConfigDirector::createClient(
    serverSdkKey: 'YOUR-SERVER-SDK-KEY',
    logLevel: LogLevel::DEBUG,
);

The SDK's own logger writes each message on one line: a control character in a value it fills in, such as a line break, is written as a space, and a value longer than 1,024 bytes is cut to its first 1,024 bytes, followed by …. A logger you pass receives every value whole. A logger that reads a config logs nothing about that read; see Hooks.

connection

The connection argument takes a ConnectionOptions object with the following optional arguments:

  • mode
    • The connection mode, ConnectionMode::Polling or ConnectionMode::Offline. There is no streaming mode on the client: the streaming process holds the streaming connection for the host. In offline mode the client never connects to ConfigDirector and serves the values you give it; see Run without a connection.
    • Defaults to ConnectionMode::Polling
  • pollingInterval
    • How long, in seconds, the host serves the values in its local store before a request asks ConfigDirector for new ones. A value below the minimum of 60 seconds is raised to 60 and a warning is logged. See When a change arrives and Polling intervals.
    • Defaults to 300 (5 minutes)
  • timeout
    • How long, in milliseconds, initialize() waits for values when the local store holds none, and how long a request to ConfigDirector may take. A request that gets no answer is sent again once within that time. It has no effect in offline mode.
    • Defaults to 3,000 (3 seconds)
  • url
    • The base URL used to connect to ConfigDirector services. It must be an http or https URL without a query or a fragment; a path is fine.
    • This should only be provided if your environment requires you to configure a proxy server in order to connect to ConfigDirector services. It has no effect in offline mode.
  • storagePath
    • The absolute path of the folder the SDK keeps its local store in, created when it is missing. See The local store.
    • Defaults to a folder for the system user in the system temp directory
  • file
    • The path of a JSON file holding the values to serve in offline mode. Only one of file and values can be given, and only in offline mode. See Run without a connection.
  • values
    • The values to serve in offline mode, as an array keyed by config key. Only one of file and values can be given, and only in offline mode. See Run without a connection.
index.php
use ConfigDirector\ConnectionOptions;

$client = ConfigDirector::createClient(
    serverSdkKey: 'YOUR-SERVER-SDK-KEY',
    connection: new ConnectionOptions(pollingInterval: 600, timeout: 5_000, storagePath: '/var/lib/my-app/configdirector'),
);

telemetry

Telemetry tuning. It is unlikely these settings need to be adjusted. Keep in mind that ConfigDirector relies on these telemetry events to provide insights and features related to the configs being used.

Each evaluation the SDK reports says which variation was served and which percentage rollout and share served it. That is how ConfigDirector counts the contexts each variation of an experiment reached. Tracked events are sent with the same reports.

The telemetry argument takes a TelemetryOptions object with the following optional arguments:

  • eventQueueLimit
    • The most evaluations and contexts one telemetry report holds, and one client holds until the request ends. The oldest ones over the limit are left out.
    • ConfigDirector keeps a count of dropped events. If the number of dropped events is higher than 50% of the total events, ConfigDirector will issue an alert in the dashboard.
    • A number between 100 and 100,000. Defaults to 5,000.
  • flushInterval
    • How often, in milliseconds, the host sends a telemetry report, however many requests it serves. See At the end of a request.
    • Defaults to 30,000 (30 seconds).
index.php
use ConfigDirector\TelemetryOptions;

$client = ConfigDirector::createClient(
    serverSdkKey: 'YOUR-SERVER-SDK-KEY',
    telemetry: new TelemetryOptions(eventQueueLimit: 10_000, flushInterval: 15_000),
);

Hooks

Hooks are events you can subscribe to in order to be notified of some key actions from the client. In order to subscribe to hooks you can provide handlers in the hooks argument, which registers them before the client can emit any event, or call on() on the client. off() removes a handler, or every handler of the event when you pass none.

index.php
use ConfigDirector\ConfigsUpdatedEvent;

$client->on('configsUpdated', function (ConfigsUpdatedEvent $event): void {
    error_log('Configs updated: ' . implode(', ', $event->keys));
});
index.php
use ConfigDirector\ClientHooks;
use ConfigDirector\ConfigEvaluatedEvent;

$client = ConfigDirector::createClient(
    serverSdkKey: 'YOUR-SERVER-SDK-KEY',
    hooks: new ClientHooks(
        configEvaluated: function (ConfigEvaluatedEvent $event): void {
            error_log("{$event->evaluation->key} evaluated to " . json_encode($event->evaluation->value));
        },
    ),
);

Each argument of ClientHooks takes one handler or a list of handlers. The following events are available:

  • clientReady
    • Called with no argument when the client first receives values and becomes ready, whether from ConfigDirector or from its offline values.
  • configsUpdated: ConfigsUpdatedEvent
    • Called each time the client receives values. The first time, keys names every config. Later values, which a client receives in a long-running process, name only the configs that are new or changed, where a config counts as changed when anything the SDK reads of it changed, such as its targeting rules, its variations, or a segment its rules use.
    • keys - The keys of the configs the values included, as described above.
    • removedKeys - The keys of the configs that are gone. Empty when nothing was removed.
  • configEvaluated: ConfigEvaluatedEvent
    • Called whenever a config is evaluated, before the read returns. This includes calls to getValue and evaluate, and values delivered to watches. getAllConfigs calls none.
    • evaluation - A ConfigEvaluation containing the details of the evaluation:
      • key - The config key that was evaluated
      • value - The value the config evaluated to, of the type of the in-code default value. It can be the in-code default value itself. For example, if the config was evaluated before the client was initialized.
      • valueId - The value ID, a stable hash of the value that you can send to a third party rather than the value. This can be useful for large values, like a JSON config, or to avoid disclosing the values themselves. It is null when the evaluation fell back to the in-code default value, and for values served in offline mode or by a test client. To report an experiment to an analytics tool, send the variation instead: the pages for Amplitude, Mixpanel, Google Analytics 4, Segment and PostHog name the event each one reads.
      • variation - The Variation that was served, with its id and name. The id stays the same when the variation is renamed, and name is null for a variation without one. It is null when the config has no variations or the in-code default value is returned.
      • isDefaultValue - Whether or not the evaluation fell back to the in-code default value.
      • reason - The reason for the evaluation resolution, an EvaluationReason. In the case the config successfully evaluated based on server-provided targeting rules, or served an offline value, it will be EvaluationReason::FoundMatch. A context without an id that is served the default targeting rule value after skipping a percentage rollout reports EvaluationReason::RolloutSkippedNoIdentifier, with isDefaultValue false; see Contexts without an id. If the evaluation had to fall back to the in-code default value, the reason will encode why the fallback was required:
        • ClientNotReady - The evaluation happened before the client had values, or after it was disposed of
        • ConfigStateMissing - The requested config key was not present in the values received from the server, usually because of an incorrect config key
        • InvalidNumber - The config was read with a number but the value received from the server could not be read as that number type
        • InvalidBoolean - The config was read with a boolean but the value received from the server was neither true nor false
        • InvalidJson - The config was read with an array but the value received from the server was not a JSON object or a JSON array
        • TypeMismatch - The config was read with a string but it is a boolean or number config
        • ValueMissing - The config key was present in the values received from the server, but it carried no value
      • context - The context that was provided to the evaluation, or null when there was none or its context kind was invalid
  • connectionError: ConnectionErrorEvent
    • Called when ConfigDirector refuses a request for values with a 4xx status other than 429, for example because the server SDK key is wrong. A refused telemetry report does not call it. It is called in the process that sent the request: during initialize(), when the client is disposed of, or during a read of a long-running process.
    • error - A ConfigDirectorConnectionException, whose status is the HTTP status ConfigDirector answered with.

The value of each EvaluationReason is its name in kebab case, such as type-mismatch for EvaluationReason::TypeMismatch, which is how logs and the test client's documentation spell them.

The client receives values during initialize(), and after that only in a long-running process or from its test client. Each time, it calls the configsUpdated handlers, then the watches on the keys the event names, then the clientReady handlers when the client has just become ready. A handler that throws is logged at error level and ignored: the other handlers still run and the read returns its value. A getValue, evaluate, getAllConfigs or track made from inside a configEvaluated handler, or from a logger, returns its value and is reported, but calls no configEvaluated handler and logs nothing.

Run without a connection

Set the connection mode to ConnectionMode::Offline to run your application without connecting to ConfigDirector, for example in a suite of UI tests where each run pins every flag to a known value. An offline client needs no server SDK key, opens no connection, creates no local store and sends nothing, so the application is invisible to the ConfigDirector dashboard: no evaluations are counted and no lifecycle state changes. Every context receives the same value and targeting rules are not applied.

Give the values in a JSON file, with one value per config key, or inline:

index.php
use ConfigDirector\ConfigDirector;
use ConfigDirector\ConnectionMode;
use ConfigDirector\ConnectionOptions;

$client = ConfigDirector::createClient(
    connection: new ConnectionOptions(mode: ConnectionMode::Offline, file: __DIR__ . '/flags/new-checkout-on.json'),
);
$client->initialize();
flags/new-checkout-on.json
{
  "new-checkout": true,
  "max-items": 20,
  "greeting": "hello",
  "theme": { "color": "blue" }
}
index.php
$client = ConfigDirector::createClient(
    connection: new ConnectionOptions(
        mode: ConnectionMode::Offline,
        values: ['new-checkout' => true, 'max-items' => 20],
    ),
);
$client->initialize();

A relative file path is resolved against the working directory of the process. The config type of each value follows from the value itself: a boolean, a number written without a decimal point or an exponent, such as 20 (integer), any other number, such as 20.0 (float), a string, or an object or array (json). Inline values follow the same rule with PHP types, exactly as the test client types them: a bool, an int, a float, a string, or an array, whether a list or a map. A value read with an in-code default value of another type returns the in-code default value, as it does against ConfigDirector.

initialize() serves the values at once: it calls the configsUpdated handlers with every config key, then the watches, then the clientReady handlers. It reads the file again on every call, so a long-running process that calls it again receives the values that changed. pollingInterval, timeout, url and storagePath have no effect.

With ConnectionMode::Offline and neither file nor values, the client is ready once initialized, and every config returns its in-code default value.

createClient throws ConfigDirectorValidationException when file and values are both given, when either is given outside offline mode, or when values has a blank config key or a value the SDK cannot serve, such as null, a float that is not finite, or an object other than stdClass. initialize() throws ConfigDirectorInitializationException when the file is missing, cannot be read, is a URL or another stream such as php://, does not hold a JSON object, or holds a value the SDK cannot serve. A test run that starts from a misspelled path fails instead of passing on in-code default values.

If you come from LaunchDarkly, a file of values is what LaunchDarkly calls "flags from files", and ConnectionMode::Offline with no values is its "offline mode".

How the SDK connects

Every other server SDK holds one streaming connection for the life of its process by default. A PHP application usually cannot: under PHP-FPM and Apache's PHP module, nothing a request creates outlives it. Asking ConfigDirector on every request is not an option either, since each request would be a poll, and each poll counts 5 minutes of service connection hours. So the SDK shares what it receives between the requests of a host, and polling is its default.

The local store

The local store is a folder where the SDK keeps the last values ConfigDirector sent and the telemetry that requests have collected but not sent yet. Every PHP process of the host that runs as the same system user shares it. Each server SDK key has a folder of its own, inside:

  • storagePath, when you set it.
  • Otherwise <system temp directory>/configdirector-<user ID> on Linux and macOS, where the user ID is the number of the system user running PHP, and <system temp directory>\configdirector on Windows.

On Linux and macOS, only the system user that created the local store can read it, and without a storagePath, web workers and command-line jobs that run as different system users, such as www-data and the user of your cron jobs, each keep a local store of their own, and each one counts as a polling connection.

The SDK does not use a local store folder that it cannot trust or write to. Every read then returns its in-code default value, the host never asks ConfigDirector, and each client logs one error that names the folder:

The local store folderWhat to do
Is a symbolic linkRemove it, or set storagePath to another folder.
Belongs to another system userSet storagePath to a folder this user owns, or run the process as the user that owns the folder.
Can be written to by other system usersRemove it, or set storagePath to a folder only this user can write to.
Cannot be created or written toSet storagePath to a folder this user can write to.

A file of the local store that cannot be read counts as an empty local store, with one error for each client.

The contexts your requests evaluate wait in the local store until the next telemetry report is sent, so their traits are on the host's disk until then.

Values that would take more memory to read than PHP's memory_limit leaves the process are not read: the request logs an error and serves in-code default values, where reading them would end it with a fatal error. Reading values takes several times their size in memory, so under the default limit of 128M this starts at about 8 MiB of values.

When a change arrives

The host serves the values in its local store for one polling interval, 5 minutes by default. The first request that finds them older asks ConfigDirector for new ones once your own code has run, so the host asks once per polling interval however many requests it serves, and ConfigDirector sees one polling connection per host. A change to your targeting rules reaches your requests within one polling interval, or in about a second while the streaming process runs.

On a new host or container the local store is empty, so the first request asks ConfigDirector during initialize() and waits up to the connection timeout, and the requests that arrive meanwhile wait for that same answer. After the timeout they serve in-code default values. When the process that asked ended before the answer arrived, the requests that follow log one warning each and serve in-code default values until the host asks again, within one polling interval.

When a request to ConfigDirector fails, the host does not ask again for one polling interval, and the requests without values meanwhile do not wait. When ConfigDirector refuses the server SDK key, or answers with another 4xx status other than 429, the host does not ask for one hour, or for the polling interval when that is longer, and the error the SDK logs names that time. After a 429 it waits the longer of the polling interval and the time ConfigDirector names, where that time counts for at most one hour.

At the end of a request

The SDK disposes of your client when the script ends, after your own shutdown functions have run, or as soon as nothing refers to the client any longer, whichever comes first. Calling dispose() yourself is optional. When the client is disposed of, it adds what it evaluated and tracked to the local store, without a network call. Then, when they are due, the request asks ConfigDirector for new values, and sends the host's telemetry report: the first request to end one flush interval after the host's last report sends what every process of the host stored, and waits up to 5 seconds for the answer.

When ConfigDirector refuses a telemetry report with a 4xx status other than 413 and 429, no process of the host collects or sends telemetry for one hour, and the request that sent the report logs a warning. A report that gets another error status, or no answer within 5 seconds, is dropped with a warning, and the next report counts what it held as dropped.

Under PHP-FPM, the response waits for that work unless your application has called fastcgi_finish_request() first. Laravel and Symfony call it when they send the response. With another framework, call it once the response is written, so that the request that polls or sends the report does not delay its own response.

Long-running processes

A client that lives longer than the telemetry flush interval, as in a queue worker, a long command, or a client kept across requests by Octane, RoadRunner or FrankenPHP, does this work during its reads. It looks at the local store again at most once a second, so it serves what another process of the host received, and calls its configsUpdated handlers and watches when values change. It asks ConfigDirector when the polling interval has passed, and adds its telemetry to the local store once per flush interval, sending the host's report when that is due, in the read or the track() call that finds it due. Disposing of such a client sends what the local store holds.

A client that lives for one web request keeps the values it initialized with until the request ends.

The streaming process

By default, a change to your targeting rules reaches your requests within one polling interval. To have it arrive in about a second, run the streaming process on each host:

CONFIGDIRECTOR_SERVER_KEY=YOUR-SERVER-SDK-KEY vendor/bin/configdirector-stream

It keeps one streaming connection to ConfigDirector open for the host, writes every change to the local store, and sends the telemetry your requests collect there, one report per flush interval, whether or not its connection is open. While it runs, your requests send no telemetry, and while its connection is open, they make no network calls for ConfigDirector. When it is stopped, or cannot reach ConfigDirector for longer than the polling interval, your requests go back to asking for values by themselves, and once it is stopped they send telemetry again, so nothing depends on it.

VariableWhat to set it to
CONFIGDIRECTOR_SERVER_KEYThe server SDK key your application uses. Required.
CONFIGDIRECTOR_APP_NAME, CONFIGDIRECTOR_APP_VERSIONThe appName and appVersion of your application's metadata, so ConfigDirector shows the host's streaming connection under your application.
CONFIGDIRECTOR_STORAGE_PATHThe storagePath of your application's ConnectionOptions, when it sets one.
CONFIGDIRECTOR_BASE_URLThe URL of your proxy, when your application connects through one.
CONFIGDIRECTOR_LOG_LEVELThe lowest PSR-3 level the command writes to standard error. Defaults to info.

The command takes no arguments and reads no .env file, and a blank variable counts as not set. Its first log line names the folder of the local store it keeps up to date.

Run one streaming process per host:

  • As the system user that runs your application, such as www-data. The local store belongs to that user, so a streaming process run as another user keeps a local store that no request reads.
  • With the same local store as your application. PHP-FPM under systemd, as Debian and Ubuntu install it, has a /tmp of its own, so there give your application and the streaming process the same storagePath.

A second streaming process on the same local store exits with an error, because a host needs one connection only. A streaming process that was killed does not keep the next one from starting. With Supervisor:

/etc/supervisor/conf.d/configdirector-stream.conf
[program:configdirector-stream]
command=php /var/www/app/vendor/bin/configdirector-stream
user=www-data
environment=CONFIGDIRECTOR_SERVER_KEY="YOUR-SERVER-SDK-KEY",CONFIGDIRECTOR_APP_NAME="YOUR-APP-NAME"
numprocs=1
autorestart=true
stopsignal=TERM

The streaming process stops on SIGTERM or SIGINT after sending the telemetry the local store holds, and exits with 0. That needs the pcntl extension. Without it, on Windows, and where disable_functions names pcntl_signal, pcntl_signal_get_handler or pcntl_signal_dispatch, a signal ends the process at once, and your requests send what the local store holds. It exits with 1, after writing why to standard error, when CONFIGDIRECTOR_SERVER_KEY is not set or a setting is rejected, when it finds no Composer autoloader, when ConfigDirector refuses the key, when another streaming process runs on the same local store, and when the local store cannot be used.

When ConfigDirector cannot be reached, the connection is closed, or nothing arrives on it for 45 seconds, the streaming process connects again by itself: after 1 to 2 seconds, then twice as long after each attempt that fails, up to 256 to 512 seconds. The first five attempts in a row are logged at info and the later ones as warnings.

To run it from your own command, such as an Artisan or a Symfony Console command, call ConfigDirector::createStreamingProcess(...)->run() with the arguments you give createClient, apart from hooks, which it does not take. run() returns after SIGTERM or SIGINT. It throws ConfigDirectorConnectionException when ConfigDirector refuses the key, and ConfigDirectorException when another streaming process runs on the same local store or the local store cannot be used, each after logging an error. The Laravel sample runs it as php artisan configdirector:stream:

app/Console/Commands/ConfigDirectorStreamCommand.php
use App\ConfigDirectorSettings;
use ConfigDirector\ConfigDirector;
use ConfigDirector\ConfigDirectorException;
use Illuminate\Console\Command;
use Illuminate\Log\LogManager;

final class ConfigDirectorStreamCommand extends Command
{
    protected $signature = 'configdirector:stream';

    protected $description = 'Keep the local store of this host up to date through a streaming connection';

    public function handle(ConfigDirectorSettings $settings, LogManager $logManager): int
    {
        $streamingProcess = ConfigDirector::createStreamingProcess(
            serverSdkKey: $settings->serverSdkKey,
            metadata: $settings->metadata,
            connection: $settings->connection,
            logger: $logManager->channel(ConfigDirectorSettings::LOG_CHANNEL),
        );

        try {
            $streamingProcess->run();
        } catch (ConfigDirectorException) {
            return self::FAILURE;
        }

        return self::SUCCESS;
    }
}

createStreamingProcess throws ConfigDirectorValidationException for the settings createClient rejects, and for ConnectionMode::Offline, since an offline application has nothing to stream. pollingInterval and timeout change nothing about a streaming process.

Retrieve config values

Retrieve config values with getValue. The first argument is the config key, the second is the in-code default value, which is returned if the config is not available or cannot be read as its type, and the third is the context targeting rules are evaluated for. The type of the in-code default value decides the type the config is read as:

index.php
use ConfigDirector\Context;

$user = new Context(id: 'user-id');

// Retrieve config values
$retries = $client->getValue('max-retries', 3, $user);
$theme = $client->getValue('theme', 'light', $user);
$newCheckout = $client->getValue('new-checkout', false, $user);

// A JSON config is read as an array, and so is its in-code default value
$limits = $client->getValue('rate-limits', ['per_minute' => 60], $user);

The type a config is read as is decided by the in-code default value you pass, not by how the config was declared in the dashboard. getValue returns a value of that same type, and PHPStan and Psalm see it: getValue('new-checkout', false) is a bool, and getValue('theme', []) an array. The in-code default value is returned when the config is missing, the client is not ready, or the value will not read as that type, so it should always be the safe choice:

  • A bool reads a boolean config. Only true and false read as a boolean, in either casing. A config holding 1 yields the in-code default value.
  • A string reads a string, enum, URL or JSON config as the server spelled it, with no parsing, so a JSON config gives its JSON text. A boolean or number config read with a string gives the in-code default value instead.
  • An int reads a whole number. A whole number the server wrote as 26.0 or 1e3 still reads as an int, and a number an int cannot hold yields the in-code default value.
  • A float reads any number.
  • An array reads a JSON config holding a JSON object, as an associative array, or a JSON array, as a list.

getValue never throws when a config is missing or a value will not read as the requested type; it returns your in-code default value instead. Which of those happened is reported by evaluate and through the configEvaluated hook. It throws ConfigDirectorValidationException only for an in-code default value of null or of any other type, such as an object, which PHPStan and Psalm also report where you pass it.

Evaluate config values with a context

Unlike client SDKs, the server SDKs are able to evaluate targeting rules for the given context locally without additional network calls.

getValue takes a Context as its last argument, which is what targeting rules are evaluated against. The same key can therefore resolve differently per user. Leave it out when there is no user to evaluate for.

The context is the last argument of getValue. Unlike client SDKs, the server SDKs are able to evaluate targeting rules for the given context locally without additional network calls.

index.php
use ConfigDirector\Context;

$user = new Context(
    id: '12345',
    name: 'Example User',
    traits: [
        'region' => 'North America', // Any arbitrary traits which can be referenced in targeting rules
    ],
);

$client->getValue('my-boolean-config-key', false, $user);

To evaluate configs for an entity other than a user, such as a tenant, set the context kind with kind:

index.php
$tenant = new Context(
    id: 'acme',
    kind: 'tenant',
    name: 'Acme Inc.',
    traits: ['plan' => 'enterprise'],
);

$client->getValue('my-boolean-config-key', false, $tenant);

Leaving kind out means user. A context kind is 1 to 64 lowercase letters, digits, dashes, or underscores. A context with an invalid context kind is ignored: the SDK logs an error, and configs are evaluated as if no context had been given.

Context takes the following named arguments, all optional:

  • id
    • The context's identifier. With the context kind, it decides the context's bucket in a percentage rollout, so changing it can move the context into a different bucket. A context without one skips percentage rollouts; see Contexts without an id.
  • kind
    • The context kind, such as tenant. Contexts of different kinds are separate contexts even when they share an identifier, and a percentage rollout can place them in different shares.
  • name
    • The context's display name.
  • traits
    • An array of arbitrary traits which can be referenced in targeting rules, keyed by the name the rule references. A trait is a string, a number, a boolean, or an array. Give a date as ISO 8601 text, such as $signedUpAt->format(DATE_ATOM), so that date conditions can compare it.
  • anonymous
    • Keeps the context out of the dashboard: it is evaluated but never persisted, and telemetry reports neither the context nor its ID.
index.php
use ConfigDirector\Context;

$user = new Context(
    id: 'user-id',
    name: 'Example User',
    traits: [
        'region' => 'North America',
        'age' => 26,
        'tags' => ['beta', 'internal'],
    ],
);

Contexts without an id

A percentage rollout places each context in a share by its id, so a context without an id skips percentage rollouts: a rollout does not apply to it, and the targeting rules after the rollout are tried, as they are after a conditional rule the context does not match. The default targeting rule value is served when none of them applies. A rule that serves a single value still applies to it. To keep an anonymous visitor in a rollout, give the context a stable id, such as a session ID.

Watch for updates

watch takes the config key, the in-code default value, a callback that receives the newly evaluated value, and the context. It returns a function that removes the watch:

index.php
use ConfigDirector\Context;

$stopWatching = $client->watch(
    'max-items',
    20,
    function (int $maxItems): void {
        error_log("max-items is now {$maxItems}");
    },
    new Context(id: 'user-id'),
);

$client->initialize();

$stopWatching();

The callback is called with the config's value each time the client receives values in which the config is new or changed, whether or not the value changed for the watch's context, and with the in-code default value when the config is removed. It is not called when you register the watch. A client receives values during initialize(), so register a watch before it to receive the first value. In a web request, that is the only time a watch fires. In a long-running process, it also fires when values change in the local store.

The in-code default value decides the type the callback receives, as it does for getValue, and PHPStan reports a callback that declares another type. unwatch($configKey, $callback) removes the first watch on the key with that callback, or every watch on the key when you pass no callback.

Track events

track reports to ConfigDirector that something happened in your application, such as a completed checkout. ConfigDirector shows tracked events on the Live feed and counts them for each variation of a running experiment; see Tracked events.

track takes the name of the event and, optionally, the context the event happened for, a value and details:

index.php
use ConfigDirector\Context;

$client->track(
    'checkout-completed',
    new Context(id: 'user-id'),
    value: 49.90,
    details: [
        'plan' => 'pro',
        'seats' => 3,
        'tags' => ['beta', 'internal'],
        'address' => ['city' => 'Lisbon'],
    ],
);

$client->track('export-finished', new Context(id: 'acme', kind: 'tenant'));

$client->track('nightly-sync-finished');
  • value is a number the event measures, such as an amount of money, a count or a duration.
  • details is an associative array describing the event. Its values are strings, numbers, booleans, or nested arrays. An empty array is sent as an empty object.

An event counts for an experiment only when it is tracked for a context with an id, the same one the experiment's config was evaluated for, so pass the context you evaluate with when you track the outcome of an experiment. Without a context, or for a context without an id, the event is still reported and counts for no experiment. For a context marked anonymous, the event is reported without the id, so it counts for no experiment either. A context with an invalid context kind is ignored as it is in an evaluation: the SDK logs an error and reports the event without a context.

track returns nothing and never throws. The event is sent with the host's next telemetry report, every 30 seconds unless you changed flushInterval; see At the end of a request. In offline mode and after dispose(), track does nothing. The SDK applies these limits, and logs one warning for each of them per request, or per flush interval in a long-running process:

LimitBeyond it
An event name of 1 to 150 charactersThe event is not reported.
1,000 tracked events in one request, and in one telemetry report of the hostFurther events of the request are not reported, and a report keeps the first 1,000 events the host's requests tracked.
Details that are an associative array, not a list, of up to 20 top-level keys and 1 KB as JSON, and that PHP can write as JSONThe details are left out and the event is still reported.
A value that is a finite numberThe value is left out and the event is still reported.

ConfigDirector applies limits of its own to the events it stores; see Limits.

Other useful client features

The client provides additional methods.

evaluate

Evaluates a config the way getValue does and returns the ConfigEvaluation behind it — the value, whether it is the in-code default value, the reason, the valueId, the variation, and the context — instead of the value alone. It takes the same arguments as getValue, and its value is of the type of the in-code default value. It is the same object the configEvaluated hook reports, so use it where the reason matters at the point of the read, such as when reporting an evaluation to another system; getValue is enough everywhere else. Like every read, it reaches configEvaluated and is counted in telemetry.

index.php
use ConfigDirector\Context;
use ConfigDirector\EvaluationReason;

$evaluation = $client->evaluate('checkout-button-color', 'blue', new Context(id: 'user-id'));

if ($evaluation->reason === EvaluationReason::ConfigStateMissing) {
    error_log('No config with this key reached the SDK.');
}

isReady

Returns a boolean indicating if the client has values to serve. It is initially false and becomes true once initialize() finds values. Until it does, every read returns its in-code default value.

getAllConfigs

Returns what every config serves to a context, as an array of ConfigState objects keyed by config key, each with the config's id, key, type, value as the server spelled it, valueId and variation. When a percentage rollout served the value, it also carries the rollout's ruleId and shareId. It takes the context to evaluate for and, optionally, the configKeys to restrict the result to. It is empty until the client is ready. PHP turns an array key made only of digits into an integer, so a config key such as 2024 is the integer key 2024 of the array.

This is intended for handing state to a client SDK to hydrate with. It records no telemetry and reaches no configEvaluated handler, since the SDK that receives the state reports its own evaluations.

unwatchAll

Removes every watch on every config. Handlers registered with on() and hooks stay.

dispose

Disposes of the client: it adds what the client evaluated and tracked to the local store and, when they are due, asks ConfigDirector for new values and sends the host's telemetry report, as described in At the end of a request. Afterwards the client is not ready, every read returns its in-code default value, and every handler, hook and watch is removed. Calling it more than once is harmless.

You do not have to call it: the SDK disposes of the client when the script ends, or as soon as nothing refers to it any longer. Call it yourself to choose the moment, such as after fastcgi_finish_request().

Exceptions

Every exception the SDK throws extends ConfigDirectorException:

  • ConfigDirectorValidationException for a setting, an in-code default value or an offline value the SDK cannot use.
  • ConfigDirectorInitializationException for offline values that initialize() cannot load.
  • ConfigDirectorConnectionException, with the HTTP status, for a request ConfigDirector refused. The connectionError hook receives it, and the streaming process's run() throws it.

When one of them has a cause in getPrevious() that the SDK raised, such as the reason a value cannot be served, that cause extends ConfigDirectorException too.

The server SDK key is marked as a sensitive parameter, so a stack trace shows SensitiveParameterValue in its place, and a dump of a client with print_r, var_dump or var_export does not show it either.

Test your code

Use the SDK's ConfigDirector\Testing namespace to test the code that reads your configs and flags. It creates a test client: the SDK's real client over an in-memory connection that your test controls. Only the connection to ConfigDirector and the telemetry are replaced. Everything else is the same code that runs in production, so the code under test behaves exactly as it does against ConfigDirector, and it needs no server SDK key, opens no network connection, creates no local store and sends no telemetry. It ships in the package, so there is nothing else to install.

tests/CheckoutServiceTest.php
use ConfigDirector\Testing\ConfigDirectorTesting;
use PHPUnit\Framework\TestCase;

final class CheckoutServiceTest extends TestCase
{
    public function testShowsTheNewCheckout(): void
    {
        $testClient = ConfigDirectorTesting::createTestClient(values: ['new-checkout' => true, 'max-items' => 20]);
        $service = new CheckoutService($testClient->client);
        $testClient->client->initialize();

        self::assertTrue($service->isNewCheckoutEnabled('user-123'));

        $testClient->setValue('new-checkout', false);
        self::assertFalse($service->isNewCheckoutEnabled('user-123'));
    }
}

$testClient->client is a ConfigDirectorClient, so it goes anywhere your code accepts one. It starts not initialized, like a production client, because the code under test usually owns the call to initialize(), which then serves the values at once. Pass the client to the code under test, as CheckoutService takes it above, rather than creating one inside: that is what lets the test hand it a client it controls. The examples use PHPUnit; any test framework works just as well.

Values

createTestClient, setValue and replaceValues take PHP values, and the config type follows from each value: a bool is a boolean config, an int an integer config, a float a float config, a string a string config, and an array a JSON config. Every value is served as an unconditional config, so every context receives the same value; a test that needs different values per context is written as one test per value. null, a float that is not finite, an object other than stdClass, or a blank key throws ConfigDirectorValidationException, and nothing changes.

Reads behave as they do in production: a value set as true and read with a string in-code default value returns that in-code default value with the type-mismatch reason, and setValue('k', 2.5) read with an int returns the in-code default value with the invalid-number reason. evaluate and the configEvaluated handlers report the reason.

Controls

ControlEffect
setValue($key, $value)Stores the value and, once the client has been initialized, delivers it: watches on the key, configsUpdated handlers and reads see it before the call returns. A value equal to the one the key has fires nothing.
removeValue($key)Removes the value. Reads return the in-code default value with the config-state-missing reason, watches on the key receive the in-code default value, and configsUpdated handlers find the key in removedKeys.
replaceValues($values)Replaces every stored value, and cancels a holdInitialization() or failInitialization() that no initialize() has used yet. Use it to reset a test client shared across tests.
holdInitialization()The next initialize() waits for the client's timeout, logs the warning a production client logs then, and returns without values, as a production client does when ConfigDirector does not answer in time.
completeInitialization()Delivers the stored values to an initialization that was held, so the client is ready and its clientReady handlers have run when the call returns. Called before initialize(), it cancels the hold.
failInitialization()The next initialize() fails as a refused server SDK key does: it returns at once without values, logs an error, and the connectionError handlers receive a ConfigDirectorConnectionException with the status 401.
trackedEvents()Returns the events the code under test tracked with track, in call order, each a TrackedEvent with name, context, value and details. An event the SDK would not report is not recorded, and a value or details the SDK would leave out are null. The limit of 1,000 events does not apply to the record. The array returned does not show later events, so call it again for them. replaceValues leaves the record as it is.
clearTrackedEvents()Forgets every event recorded so far. A test client shared across tests needs this and replaceValues to reset.
tests/CheckoutServiceTest.php
use ConfigDirector\Context;

$testClient = ConfigDirectorTesting::createTestClient(values: ['new-checkout' => true], timeout: 500);
$service = new CheckoutService($testClient->client);
$testClient->failInitialization();
$testClient->client->initialize();

self::assertFalse($testClient->client->isReady());
self::assertFalse($service->isNewCheckoutEnabled('user-123'));

$testClient->client->track('checkout-completed', new Context(id: 'user-123'), value: 49.9);

self::assertSame('checkout-completed', $testClient->trackedEvents()[0]->name);
self::assertSame(49.9, $testClient->trackedEvents()[0]->value);

Options

createTestClient(values:, timeout:, logger:) takes timeout, in milliseconds, the client's connection timeout, which is how long a held initialize() waits and defaults to 3,000; and logger, a PSR-3 logger, which defaults to the SDK's error_log logger as for a production client.

What to expect

  • Watches and handlers run inside the call that delivers values, initialize(), setValue, removeValue, replaceValues or completeInitialization, so an assertion can follow the call directly. A change made from inside a handler or a watch is delivered after the change being handled.
  • The first values fire configsUpdated before clientReady, as in production. Handlers and watches registered before initialize() see them.
  • A change made while the client is not initialized, or after a held or failed initialize(), reaches it once it receives values again.
  • A handler or watch that throws is logged and ignored, as it is in production.
  • After dispose(), reads return the in-code default value with the client-not-ready reason, every handler and watch is removed, and track records nothing.