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#
composer require flagswift/flagswift-phpIt needs PHP 8.1 or newer and has no runtime dependencies. It uses ext-curl when present and PHP streams otherwise.
Placeholder package name
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.
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.
| Store | Description |
|---|---|
| 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. |
| ArrayStore | Per process. Good for queue workers, Octane and tests. Under FPM every request starts empty and downloads again. |
| ConfigStore | An interface with read(): ?array and write(array $record). Implement it for Redis or anything else. |
Not ArrayStore under FPM
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.
| Argument | Type | Description |
|---|---|---|
| apiKey, baseUrl* | string | A server or admin key and your server address. |
| environment | ?string | Only for project-wide keys. |
| store | ?ConfigStore | Where the configuration lives. Default ArrayStore. |
| refreshInterval | float | Seconds before the stored copy is revalidated. Default 30. Negative never refreshes. |
| fallbacks | array | Served for unknown flags, and when there is no configuration. |
| bootstrap | ?array | A saved payload for when the store is empty. |
| timeout, initTimeout | float | Seconds. Defaults 2 and 5. initTimeout caps a load with nothing stored. |
| maxRetries, failureBackoff | int, float | Defaults 2 retries, and 5 seconds before retrying a failed refresh (doubling to five minutes). |
| autoExposures | bool | Queue an exposure on every single-flag read. Default false. |
| onError | callable | Called 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.
$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.
$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.
| Situation | Description |
|---|---|
| Fresh copy | A copy younger than refreshInterval never touches the network. |
| Stale copy | The first check revalidates with a conditional request. A warm cache never waits on retries. |
| A refresh fails | Every 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 workers | In 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.
| Situation | Description |
|---|---|
| A refresh fails | The last good configuration and its ETag stay. The failure shows in status() and goes to onError. |
| First load, nothing stored | You get your fallbacks, then false. The cold load is bounded by initTimeout, and a bootstrap payload is used at once. |
| New process during an outage | FileStore 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 hashVersion | The payload is refused rather than silently putting people in the wrong bucket. |
| Reading the state | status() 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.
$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 shutdownPHP 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.
| Argument | Type | Description |
|---|---|---|
| apiKey, baseUrl* | string | Throw FlagSwiftException with MISSING_API_KEY or MISSING_BASE_URL. |
| environment | ?string | Only for project-wide keys. |
| refreshInterval | float | Seconds. Default 30. Negative never refreshes. |
| timeout | float | Seconds. Default 2. |
| initTimeout | float | Seconds. Default 5. Caps a load with nothing stored (all attempts, retries and sleeps); the request then serves fallbacks. |
| maxRetries | int | Default 2. |
| failureBackoff | float | Seconds before retrying after a failed refresh. Default 5, doubling to five minutes. |
| fallbacks | array | Served for unknown flags or without a configuration. |
| bootstrap | ?array | A saved payload for when the store is empty. |
| store | ?ConfigStore | Where the configuration lives. Default ArrayStore. |
| reportErrors | bool | Default true. Counts are sent when the request ends. |
| onError, transport, clock, sleep | callable | Callback and test hooks. |
| Method | Description |
|---|---|
| Client::fromArray(array $options) | Builds a client from the constructor arguments by name. |
| evaluate(string $flagKey, string|array|null $user = null): array | enabled, 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(): array | A result per flag; the known keys. |
| snapshot(): ?array / status(): array | The loaded payload; initialized, environment, version, flagCount, fetchedAt, lastError, errorCount and consecutiveFailures. |
| refresh(): bool | Fetch now, ignoring freshness. False (and onError) on failure; the last good configuration stays. |
| trackExposure(flag, user): void | Evaluates locally and queues the outcome this person got. Never throws. |
| track(event, user, value = null): void | Records an outcome after the person's pending exposures. The value is optional. |
| flushAnalytics(): void | Sends what is queued now. Pass autoExposures: true to queue an exposure on every single-flag read (default false). |
| flush(): void | Send pending error counts now. It also runs at shutdown. |
| Store | Description |
|---|---|
| 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). |
| ArrayStore | Per process. Suits queue workers and tests; in FPM it downloads on every request. |
| ConfigStore interface | read(): ?array and write(array $record): implement it for Redis or anything else. |