Skip to content
FlagSwiftDocs

PHP SDK

A shared config cache for FPM, CLI and Octane.

Use this SDK in plain PHP, Symfony, Slim and any framework without a dedicated package. For Laravel, the Laravel package wraps this SDK with a facade, a Blade directive and middleware. Flags are evaluated locally from a configuration your requests share, so a check never costs a network call. Options and behaviour every SDK shares are on Options and behaviour.

At a glance#

Install
composer require flagswift/flagswift-php
Requires
PHP 8.1+
Key
Server key (fs_srv_)
Evaluates
Locally, in memory
Real-time updates
No, it polls
Works offline from
Shared config store
Outcome analytics
Yes
Verified
Tested against shared vectors

Options, user context and behaviour every SDK shares are on Options and behaviour. To compare SDKs, see SDK features.

Installation#

bash
composer require flagswift/flagswift-php

It needs PHP 8.1 or newer and has no runtime dependencies. It uses ext-curl when present and PHP streams otherwise.

Placeholder package name

The Packagist name is a placeholder until the publishing location is decided, and nothing is published yet. Install from the repository for now.

Initialization#

You need a server key (fs_srv_…) or admin key with the evaluation:read scope, and the address of your FlagSwift server. There is no default host. PHP usually has no process to poll from, so the configuration lives in a store that requests share. Pick one and create the client.

flags.php
use FlagSwiftClient;
use FlagSwiftFileStore;

$flags = new Client(
    apiKey: getenv('FLAGSWIFT_KEY'),           // fs_srv_ or fs_admin_ key with evaluation:read
    baseUrl: 'https://flags.example.com',       // required: your FlagSwift server
    store: new FileStore('/var/cache/myapp/flagswift.json'),
    fallbacks: ['new-checkout' => false],
);

The first check in a request reads the store. If the stored copy is older than refreshInterval, the client revalidates with a conditional request, which costs almost nothing when nothing changed.

Choose a store#

The store is where the configuration lives between requests. It is the single most important choice in PHP.

Stores
StoreDescription
FileStore($path)Works everywhere. Atomic write, mode 0600, shared by every process that can read the file. Use a path outside the web root.
ApcuStore($key = 'flagswift:config')Shared memory inside one PHP-FPM pool. Needs ext-apcu.
ArrayStorePer process. Good for queue workers, Octane and tests. Under FPM every request starts empty and downloads again.
ConfigStoreAn interface with read(): ?array and write(array $record). Implement it for Redis or anything else.

Not ArrayStore under FPM

With ArrayStore in PHP-FPM, each request downloads the configuration. Use FileStore or ApcuStore there.

Connection options#

apiKey and baseUrl are required. Setup mistakes throw FlagSwiftException with MISSING_API_KEY or MISSING_BASE_URL. Everything else has a default.

Common arguments of Client
ArgumentTypeDescription
apiKey, baseUrl*stringA server or admin key and your server address.
environment?stringOnly for project-wide keys.
store?ConfigStoreWhere the configuration lives. Default ArrayStore.
refreshIntervalfloatSeconds before the stored copy is revalidated. Default 30. Negative never refreshes.
fallbacksarrayServed for unknown flags, and when there is no configuration.
bootstrap?arrayA saved payload for when the store is empty.
timeout, initTimeoutfloatSeconds. Defaults 2 and 5. initTimeout caps a load with nothing stored.
maxRetries, failureBackoffint, floatDefaults 2 retries, and 5 seconds before retrying a failed refresh (doubling to five minutes).
autoExposuresboolQueue an exposure on every single-flag read. Default false.
onErrorcallableCalled with the Throwable when a fetch fails.

Check flags#

The user is an identifier string, a list of identifiers, or an array with identifier(s), account(s), device(s) and attributes. Evaluation never throws. A flag the server does not know gives your fallbacks value, then false.

php
$user = ['identifier' => 'user-42', 'account' => 'acme', 'attributes' => ['plan' => 'pro']];

if ($flags->isEnabled('new-checkout', $user)) {
    // new flow
}

// Your own default when the flag is not found.
$beta = $flags->isEnabled('beta-banner', $user, true);

// The reason behind an answer: enabled, reason, found, plus variant and value.
$result = $flags->evaluate('new-checkout', $user);

Check variants and values#

A flag can serve a named variant, such as a button colour or a plan limit. variant gives its key and value gives what it carries, or the boolean for a plain flag.

php
$variant = $flags->variant('checkout-layout', 'user-42');   // 'compact', 'wide' or null
$limit   = $flags->value('seat-limit', 'user-42', 5);       // the variant's value, or 5

$everything = $flags->all($user);                           // a result per flag
$keys       = $flags->flagKeys();

Describe the person#

Percentage rollouts bucket on the first identifier. Accounts and devices help targeting rules, and attributes such as plan feed rule conditions. Attributes stay on your server. A guest with no identifier gets the “off” side of a percentage rollout.

How the configuration stays fresh#

PHP has no background poller and no real-time stream, so freshness is checked per request.

Refresh behaviour
SituationDescription
Fresh copyA copy younger than refreshInterval never touches the network.
Stale copyThe first check revalidates with a conditional request. A warm cache never waits on retries.
A refresh failsEvery process sharing the store backs off for failureBackoff seconds, doubling to five minutes, instead of stampeding an unhealthy server. The last good configuration keeps serving.
Force it$flags->refresh() fetches now and returns false (and calls onError) on failure.
Long-lived workersIn queue workers and Octane the same check repeats after each interval.

Offline and errors#

Once a configuration is stored, evaluation is local. It keeps working with no internet and through a FlagSwift outage, and it never throws.

What happens when something goes wrong
SituationDescription
A refresh failsThe last good configuration and its ETag stay. The failure shows in status() and goes to onError.
First load, nothing storedYou get your fallbacks, then false. The cold load is bounded by initTimeout, and a bootstrap payload is used at once.
New process during an outageFileStore and ApcuStore keep the configuration across requests and restarts, so it serves the persisted copy. ArrayStore does not outlive the process. A corrupt store record is ignored.
Server on an unknown hashVersionThe payload is refused rather than silently putting people in the wrong bucket.
Reading the statestatus() has lastError, errorCount, consecutiveFailures, flagCount and fetchedAt.

Outcome analytics#

Report what people saw and what they did so FlagSwift can compare variants. Nothing is sent unless you call these or set autoExposures: true, and only the person's identifier, the flag, the variant and the event name leave your server.

php
$flags->trackExposure('button-colour', $user);   // this person was shown the flag's current outcome
$flags->track('purchase', $user, 19.99);         // what they did; the value is optional
$flags->flushAnalytics();                        // send now; otherwise it is sent at shutdown

PHP has no background thread, so items are queued in memory and sent when the request ends, after the response is flushed where fastcgi_finish_request exists. See Outcomes for how results are read in the console.

Reference#

Package flagswift/flagswift-php, PHP 8.1 or newer. PHP has no process to poll from, so the configuration lives in a store shared between requests. The first check of a request revalidates when the stored copy is older than refreshInterval. A warm cache never waits on a retry, and a failed refresh sets a shared backoff so workers do not stampede.

PHP client constructor
ArgumentTypeDescription
apiKey, baseUrl*stringThrow FlagSwiftException with MISSING_API_KEY or MISSING_BASE_URL.
environment?stringOnly for project-wide keys.
refreshIntervalfloatSeconds. Default 30. Negative never refreshes.
timeoutfloatSeconds. Default 2.
initTimeoutfloatSeconds. Default 5. Caps a load with nothing stored (all attempts, retries and sleeps); the request then serves fallbacks.
maxRetriesintDefault 2.
failureBackofffloatSeconds before retrying after a failed refresh. Default 5, doubling to five minutes.
fallbacksarrayServed for unknown flags or without a configuration.
bootstrap?arrayA saved payload for when the store is empty.
store?ConfigStoreWhere the configuration lives. Default ArrayStore.
reportErrorsboolDefault true. Counts are sent when the request ends.
onError, transport, clock, sleepcallableCallback and test hooks.
PHP client methods
MethodDescription
Client::fromArray(array $options)Builds a client from the constructor arguments by name.
evaluate(string $flagKey, string|array|null $user = null): arrayenabled, reason, found, plus variant and value. The user is an identifier, a list, or an array with identifier(s), account(s), device(s) and attributes.
isEnabled(flagKey, user, ?bool $fallback)The fallback applies when the flag is not found.
variant(flagKey, user) / value(flagKey, user, fallback)Variant key and value.
all(user): array / flagKeys(): arrayA result per flag; the known keys.
snapshot(): ?array / status(): arrayThe loaded payload; initialized, environment, version, flagCount, fetchedAt, lastError, errorCount and consecutiveFailures.
refresh(): boolFetch now, ignoring freshness. False (and onError) on failure; the last good configuration stays.
trackExposure(flag, user): voidEvaluates locally and queues the outcome this person got. Never throws.
track(event, user, value = null): voidRecords an outcome after the person's pending exposures. The value is optional.
flushAnalytics(): voidSends what is queued now. Pass autoExposures: true to queue an exposure on every single-flag read (default false).
flush(): voidSend pending error counts now. It also runs at shutdown.
PHP stores
StoreDescription
FileStore($path)Works everywhere. Shared by every process that can read the file.
ApcuStore($key = 'flagswift:config')Shared memory inside one FPM pool. Throws APCU_MISSING without ext-apcu (untested here).
ArrayStorePer process. Suits queue workers and tests; in FPM it downloads on every request.
ConfigStore interfaceread(): ?array and write(array $record): implement it for Redis or anything else.