SDKs
PHP SDK
nanoflags/nanoflags package is built for the way PHP runs: one request at a time, nothing kept between requests. Flags are evaluated locally against a signed configuration that is shared between requests through a cache and revalidated with a cheap conditional request. A variation call never throws.On this page
Install
composer require nanoflags/nanoflags
composer require nanoflags/openfeature-provider # optional: OpenFeature provider- Published on Packagist as nanoflags/nanoflags 0.2.0 and nanoflags/openfeature-provider 0.2.0. PHP 8.1 or newer, framework-agnostic (Laravel, Symfony, Slim, WordPress, plain PHP).
- Recommended extensions:
sodium(signature verification; bundled with most PHP builds, orparagonie/sodium_compat),curl,apcu(the default shared cache under PHP-FPM) andintl(faster Unicode normalisation; a polyfill is used otherwise). - PSR-16 caches and PSR-18 HTTP clients plug in; the built-in transport uses ext-curl, or PHP streams without it. The engine is a native port of the NanoFlags engine, tested against the shared fixtures generated from the reference engine (21,998 evaluation cases), so it gives the same results as every other SDK.
- Apache-2.0. Source in nanoflags-sdk/php.
Quickstart
Copy a server key (nf_srv_…) from Settings → SDK keys in the dashboard and keep it in an environment variable. Pass onError (or a PSR-3 logger) to the constructor, so the first load's errors are reported too.
use NanoFlags\Client;
use NanoFlags\NanoFlagsException;
$flags = new Client(
getenv('NANOFLAGS_SDK_KEY'), // nf_srv_… (server view) or nf_pub_… (client-exposed flags only)
service: 'checkout-api', // shown in "which revision is each service running"
onError: fn (NanoFlagsException $e) => error_log("nanoflags {$e->errorCode}: {$e->getMessage()}"),
);
$user = ['key' => $userId, 'plan' => 'beta', 'country' => 'DE'];
if ($flags->boolVariation('new-checkout', false, $user)) {
// …
}- Constructing a client does no I/O. The first evaluation (or
status()) loads the configuration from the shared cache, and from the edge only when the cached copy is due for revalidation. - There is no readiness to wait for: within a request, the configuration does not change.
status()saysready,staleornot-ready, andlastError()holds the latest error. - Without a listener or logger, errors are only visible through
lastError(). The base URL defaults to the hosted edge,https://edge.nanoflags.io.
Typed variations and details
Each variation takes the flag key, the value to serve when the flag cannot be evaluated, and the context: an associative array of JSON-like attributes. key is the stable identity used for percentage rollouts.
$enabled = $flags->boolVariation('new-checkout', false, $user);
$accent = $flags->stringVariation('accent', 'blue', $user);
$limit = $flags->numberVariation('rate-limit', 100, $user); // int for whole numbers, else float
$layout = $flags->jsonVariation('layout', ['cols' => 3], $user); // JSON objects as associative arrays
$every = $flags->allFlags($user); // no telemetry
$d = $flags->boolVariationDetail('new-checkout', false, $user);
printf("%s %s %s r%d\n", var_export($d->value, true), $d->reason, $d->ruleId, $d->revision); // true rule_match beta r57
foreach ($d->trace as $step) { /* the same steps the dashboard shows */ }| Property | Meaning |
|---|---|
value | The value served (your default in the fallback cases). |
reason | rule_match, default (no rule matched), off (flag disabled), flag_not_found, error (wrong type or malformed configuration) |
ruleIndex · ruleId | The matching rule (zero-based index), or null. |
inRollout · bucket | For percentage rollouts: whether the key is inside the allocation, and its bucket (0 to 99.99). |
revision | The configuration revision the result came from. |
trace | A list of TraceStep explaining the decision step by step. |
error · json() · typeName() | Why reason is error; the raw value as JSON text and its type name. |
You get your default when nothing is loaded, when the flag is unknown, or when it serves a value of another type. A disabled flag is not a fallback case: it returns the flag's configured off value. evaluate($key, $default, $context) returns the engine result without a type check.
How it works in PHP
| Situation | What happens |
|---|---|
| First evaluation of a request, cached bundle revalidated less than cacheTtl (30 s) ago | No network: the cached bundle is used (status ready). |
| Cached bundle older than cacheTtl | One conditional GET /v1/bundle with the cached ETag (timeout, 3 s). Usually 304 Not Modified; a new revision is verified, cached and used. |
| Edge unreachable, slow or failing | The cached bundle keeps serving (status stale); the edge is asked again after retryInterval (5 s), not on every request. |
| Nothing cached and the edge unreachable | bootstrap if given, otherwise your defaults (status not-ready). |
| Long-running PHP (Octane, RoadRunner, Swoole, queue workers) | Reuse one client: it revalidates by itself once cacheTtl has passed. Call flush() after each job or request to send telemetry. |
The cache entry holds the exact signed bytes, and every read verifies the signature again (the cache is outside the trust boundary), with the parsed result memoised per process. A client never moves back to an older revision than the one it has, even when the edge itself serves its last known good copy.
Choosing the cache
use NanoFlags\Client;
use NanoFlags\Store\{ApcuStore, FileStore, Psr16Store};
new Client($key); // default: APCu when enabled, else a private dir in sys_get_temp_dir()
new Client($key, cache: new FileStore('/var/cache/nanoflags')); // shared by every process of the machine
new Client($key, cache: Cache::store('redis')); // Laravel: any PSR-16 cache, shared by all servers
new Client($key, cache: new Symfony\Component\Cache\Psr16Cache($pool));
new Client($key, cache: false); // no cache: every client fetches (CLI scripts)- APCu is per PHP-FPM pool and machine. A Redis or Memcached PSR-16 cache shares one bundle, and one revalidation, across a fleet.
- Directories are created with mode
0700and files written atomically with mode0600. The cache holds flag rules, never the SDK key. offline: truenever touches the network (bootstrap and cache only, no telemetry), for tests and air-gapped builds.bootstrap:takes a bundle (JSON text or a decoded array) used when nothing better is available.
Sync daemon
With the optional daemon, web requests never wait for the edge: vendor/bin/nanoflags-sync keeps the shared cache current over the edge's event stream (/v1/stream) with a safety poll, and the web workers only read the cache.
// the same key, base URL and cache as the web workers
return new NanoFlags\Client(getenv('NANOFLAGS_SDK_KEY'), service: 'web', cache: new NanoFlags\Store\FileStore('/var/cache/nanoflags'));vendor/bin/nanoflags-sync config/nanoflags.php # runs until stopped (systemd, supervisord, a sidecar)
vendor/bin/nanoflags-sync config/nanoflags.php --interval=15 # safety poll every 15 s (default 30)
vendor/bin/nanoflags-sync config/nanoflags.php --once # one revalidation (cron); exit code 1 when not current// never fetch: read what the daemon cached
$flags = new Client(getenv('NANOFLAGS_SDK_KEY'), service: 'web', cache: new FileStore('/var/cache/nanoflags'), refresh: false);- The config file returns a
NanoFlags\Client(or a callable that returns one) configured with the same SDK key, base URL and cache as the web workers. The daemon prints each new status and revision to stdout, and errors to stderr. - APCu is not shared with a CLI process: use a directory or a networked PSR-16 cache with the daemon.
- Without
refresh: false, workers still revalidate on their own whenever the daemon falls behind.--no-streampolls only. The daemon runs$client->run($pollInterval, $stream, $duration, $onSync), which you can also call from your own long-running command.
Laravel and Symfony
$this->app->scoped(NanoFlags\Client::class, fn () => new NanoFlags\Client(
config('services.nanoflags.key'),
service: config('app.name'),
cache: Cache::store(), // any configured store
logger: Log::channel(),
));
// usage: app(NanoFlags\Client::class)->boolVariation('new-checkout', false, ['key' => (string) auth()->id()])Under Octane use scoped as above (a fresh client per request, one cache) or a singleton plus flush() in a terminating callback.
services:
nanoflags.cache:
class: Symfony\Component\Cache\Psr16Cache
arguments: ['@cache.app']
NanoFlags\Client:
arguments:
$sdkKey: '%env(NANOFLAGS_SDK_KEY)%'
$service: 'checkout-api'
$cache: '@nanoflags.cache'
$logger: '@logger'A PSR-18 client plugs in with new Client($key, http: $psr18Client, requestFactory: $psr17Factory, streamFactory: $psr17Factory). Give it a short timeout (a bundle request can run on the request path) and disable redirects. The built-in curl transport honours HTTPS_PROXY / NO_PROXY and CURL_CA_BUNDLE / SSL_CERT_FILE.
Test sessions
A shared test session, created in the dashboard (Scenarios → Shared test session), pins a configuration snapshot and a synthetic context to a token (nf_ts_…). A service that receives the token in the x-nanoflags-session header evaluates against that snapshot, with the session context plus your context (yours wins), for that request only. Sampled events from a session carry its id. Shared test sessions are part of the Scale plan.
// Plain PHP / Laravel / Symfony: the header of the current request
$f = $flags->sessionFromGlobals(); // or $flags->session($request->headers->get('x-nanoflags-session'))
$f->boolVariation('checkout-v2', false, ['key' => $userId]); // session-scoped while the session is active
$f->isActive(); $f->id(); $f->expiresAt(); $f->revision();
$http->request('GET', $pricingUrl, ['headers' => $f->headers()]); // the next service joins the session ([] outside one)
// PSR-15 (Slim, Mezzio, …): the evaluator becomes the request attribute "nanoflags.flags"
$app->add(new NanoFlags\SessionMiddleware($flags));
$f = $request->getAttribute(NanoFlags\SessionMiddleware::ATTRIBUTE);session($token, $service = null)asks the edge once per token and service (GET /v1/session, the token inX-NanoFlags-Session,$service(default: the client'sservice) inX-NanoFlags-Service).sessionFromGlobals()reads the header of the current request from$_SERVER.- It never throws: an unknown, expired, revoked or not permitted token (or a failed lookup, reported as a
sessionerror) falls back to the normal configuration, and the evaluator behaves exactly like the client, so one code path serves normal traffic and tests. When a session expires mid-request,isActive()turns false and evaluations continue on the published configuration. headers()returns['x-nanoflags-session' => token]for a well-formed token, also when this service could not resolve it, and[]otherwise: always safe to merge into a downstream request.- Caching. An active session is kept until it expires, in the client and in the shared cache, under its own key (a hash of service and token: the token itself is never stored, and the bundle entry every other request uses is never touched), with the session's expiry as TTL (at most 1 hour, then it is asked for again). Unknown tokens are remembered for 15 s and failed lookups for 3 s in the client only, so arbitrary header values cannot fill the shared cache.
offline: trueresolves nothing; withrefresh: falsesessions are still fetched on demand (the sync daemon cannot know the tokens). NanoFlags\SessionMiddlewareimplements PSR-15'sMiddlewareInterface, which every PSR-15 framework already installs (psr/http-server-middleware). It is not a dependency of this package, so do not load the class without it.- A session changes which snapshot and context an evaluation uses. It grants no data access and must not be used for authorization. Client keys only receive client-exposed flags, in sessions too. Session bundles are not signed; verification does not apply to them. A revoked session keeps working where it is cached until it expires.
Signature verification
Every bundle, from the edge and from the cache, is checked (Ed25519 over the canonical string, by key id) before it is used. With the hosted edge this is on by default with the production keys embedded in the package (Keys::OFFICIAL_SIGNING_KEYS), and unsigned bundles are refused. The raw signed bytes are hashed exactly as served.
// Self-hosted or proxied edge: pin your keys and require signatures
$flags = new Client($key,
baseUrl: 'https://flags.internal.example',
verify: ['publicKeys' => [['kty' => 'OKP', 'crv' => 'Ed25519', 'x' => '…', 'kid' => 'k1']], 'require' => true],
);- A bundle that fails verification is not used: the cached one stays, and
onErrorreceives codesignature. - A bundle naming an unknown key id (a key rotation) loads
GET /v1/keysonce, at most once a minute, shared through the cache.verify: true(or'fetchKeys' => true) uses the edge's/v1/keysfor a self-hosted edge;verify: falseturns verification off. - Once a bundle of one environment was accepted, bundles signed for another environment are refused. Without ext-sodium or
paragonie/sodium_compat, verified mode refuses every bundle and aconfigerror says so. - Bundles for a newer evaluation engine than
Client::SUPPORTED_ENGINE_VERSIONare refused (codeengine) and the cached configuration stays in use: upgrade the package. The canonical string is described in Signatures.
Telemetry and redaction
A sampled 10 % of evaluations are recorded. By default, context values never leave the process: only the names (and value types) of the attributes the flag's rules use, for example {"plan": "string"}. Events are buffered in the cache and sent at most once per flushInterval (10 s) at the end of a request, with the service report at least every reportInterval (60 s).
$flags = new Client($key,
events: [
'sampleRate' => 0.05,
'redact' => fn (array $ctx) => ['plan' => $ctx['plan'] ?? null], // what leaves the process
],
);
$quiet = new Client($key, events: false); // no telemetry at allTelemetry is best effort: never retried, and concurrent requests can drop some buffered events. flush() sends queued events now; long-running workers should call it after each job.
OpenFeature provider
composer require nanoflags/openfeature-provideruse NanoFlags\Client;
use NanoFlags\OpenFeature\NanoFlagsProvider;
use OpenFeature\OpenFeatureAPI;
use OpenFeature\implementation\flags\Attributes;
use OpenFeature\implementation\flags\EvaluationContext;
$api = OpenFeatureAPI::getInstance();
$api->setProvider(new NanoFlagsProvider(new Client(getenv('NANOFLAGS_SDK_KEY'), service: 'checkout-api')));
$client = $api->getClient();
$enabled = $client->getBooleanValue('new-checkout', false, new EvaluationContext($userId, new Attributes(['plan' => 'beta'])));
$details = $client->getStringDetails('accent', 'blue', new EvaluationContext($userId));- For
open-feature/sdk2.x. Configure theClientexactly as without OpenFeature (cache, verification, telemetry,refresh: falsewith the sync daemon). - The targeting key becomes the NanoFlags
key(and wins over an attribute namedkey). Reasons:DISABLED,DEFAULT,TARGETING_MATCH,SPLIT(the variant is the rule id). Errors:FLAG_NOT_FOUND(orPROVIDER_NOT_READYwhile nothing is loaded),TYPE_MISMATCH,GENERAL. Flag metadata carriesrevision. - The integer accessor needs a whole number; the float accessor accepts any number. The object accessor returns JSON objects and arrays as PHP arrays.
- Test sessions: pass the request's evaluator as the second argument,
new NanoFlagsProvider($flags, fn () => $flags->sessionFromGlobals())(or the evaluatorNanoFlags\SessionMiddlewareput on the request). Outside a session it behaves exactly like the client. - The PHP OpenFeature SDK has no provider events: status and errors are on the
Client(status(),lastError(),onError()).
API and options
| Argument | Default | Description |
|---|---|---|
baseUrl | https://edge.nanoflags.io | Edge URL. |
service | 'unknown' | The name this process reports under. |
cache | APCu or a temp dir | A Store, any PSR-16 cache, or false. See Choosing the cache. |
cacheTtl · retryInterval | 30.0 · 5.0 | Seconds before a cached bundle is revalidated, and between attempts while the edge fails. |
refresh | true | false: never fetch, only read the cache (with the sync daemon). |
offline | false | No network at all: bootstrap and cache only, no telemetry. |
timeout | 3.0 | Seconds for a bundle request. |
bootstrap | none | A bundle (JSON text or decoded array) used when nothing better is available. |
verify | on for the hosted edge | true, false or ['publicKeys' => …, 'require' => …, 'fetchKeys' => …]. |
events | 10 % sampled | false or ['sampleRate', 'flushInterval', 'reportInterval', 'timeout', 'redact']. |
http · requestFactory · streamFactory | curl or streams | A PSR-18 client with PSR-17 factories. |
logger · onError | none | A PSR-3 logger, and an error listener registered before the first load. |
| Method | Description |
|---|---|
boolVariation · stringVariation · numberVariation · jsonVariation | Typed value: ($key, $default, $context = null). |
*VariationDetail · evaluate | An EvaluationDetail. |
allFlags · allFlagsDetail | Every flag of the configuration (no telemetry). |
status() · revision() · source() · isReady() · bundleJson() | State: not-ready / ready / stale; source network, cache or bootstrap. |
session($token, $service = null) · sessionFromGlobals($service = null) | A SessionEvaluator for a test session: the typed variations and details, evaluate, isActive(), id(), expiresAt(), revision(), headers(). |
onError(callable) · lastError() | Add an error listener (returns a function that removes it); the latest error. |
refresh() · flush() · run(…) | Revalidate now (returns whether a current configuration is in use), send telemetry now, the sync loop. |
Error codes
Errors reach onError as NanoFlagsException with an errorCode (and httpStatus for unauthorized and http): network, unauthorized, http, invalid_bundle, store, config, signature, engine, session. A failed update never changes the configuration in use, and nothing is thrown from a variation call.
Troubleshooting
- Every variation returns the default. Check
status()andlastError().unauthorizedmeans the key was rejected; with a browser key (nf_pub_…) only client-exposed flags are delivered. - Every request fetches from the edge. That is what
cache: falsedoes. Otherwise the cache cannot be read or written: look for errors with codestore, and check that the directory (or the PSR-16 backend) is writable by the PHP user. - The daemon runs but workers stay on an old revision. The daemon and the workers must use the same key, base URL and cache. APCu is not shared between a CLI process and PHP-FPM.
- Errors with code
configabout sodium. Install ext-sodium orparagonie/sodium_compat; without one of them every signed bundle is refused. - No live WebSocket. The PHP SDK does not use
/v1/live: request-scoped PHP revalidates the shared cache instead, and the sync daemon uses the event stream.