Skip to content
NanoFlags
Start free

SDKs

PHP SDK

The 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.

Install

sh
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, or paragonie/sodium_compat), curl, apcu (the default shared cache under PHP-FPM) and intl (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.

index.php
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() says ready, stale or not-ready, and lastError() 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.

php
$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 */ }
PropertyMeaning
valueThe value served (your default in the fallback cases).
reasonrule_match, default (no rule matched), off (flag disabled), flag_not_found, error (wrong type or malformed configuration)
ruleIndex · ruleIdThe matching rule (zero-based index), or null.
inRollout · bucketFor percentage rollouts: whether the key is inside the allocation, and its bucket (0 to 99.99).
revisionThe configuration revision the result came from.
traceA 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

SituationWhat happens
First evaluation of a request, cached bundle revalidated less than cacheTtl (30 s) agoNo network: the cached bundle is used (status ready).
Cached bundle older than cacheTtlOne 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 failingThe cached bundle keeps serving (status stale); the edge is asked again after retryInterval (5 s), not on every request.
Nothing cached and the edge unreachablebootstrap 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

php
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 0700 and files written atomically with mode 0600. The cache holds flag rules, never the SDK key.
  • offline: true never 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.

config/nanoflags.php
// 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'));
sh
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
worker.php
// 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-stream polls only. The daemon runs $client->run($pollInterval, $stream, $duration, $onSync), which you can also call from your own long-running command.

Laravel and Symfony

app/Providers/AppServiceProvider.php
$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.

config/services.yaml
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.

php
// 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 in X-NanoFlags-Session, $service (default: the client's service) in X-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 session error) 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: true resolves nothing; with refresh: false sessions are still fetched on demand (the sync daemon cannot know the tokens).
  • NanoFlags\SessionMiddleware implements PSR-15's MiddlewareInterface, 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.

php
// 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 onError receives code signature.
  • A bundle naming an unknown key id (a key rotation) loads GET /v1/keys once, at most once a minute, shared through the cache. verify: true (or 'fetchKeys' => true) uses the edge's /v1/keys for a self-hosted edge; verify: false turns 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 a config error says so.
  • Bundles for a newer evaluation engine than Client::SUPPORTED_ENGINE_VERSION are refused (code engine) 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).

php
$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 all

Telemetry 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

sh
composer require nanoflags/openfeature-provider
php
use 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/sdk 2.x. Configure the Client exactly as without OpenFeature (cache, verification, telemetry, refresh: false with the sync daemon).
  • The targeting key becomes the NanoFlags key (and wins over an attribute named key). Reasons: DISABLED, DEFAULT, TARGETING_MATCH, SPLIT (the variant is the rule id). Errors: FLAG_NOT_FOUND (or PROVIDER_NOT_READY while nothing is loaded), TYPE_MISMATCH, GENERAL. Flag metadata carries revision.
  • 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 evaluator NanoFlags\SessionMiddleware put 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

ArgumentDefaultDescription
baseUrlhttps://edge.nanoflags.ioEdge URL.
service'unknown'The name this process reports under.
cacheAPCu or a temp dirA Store, any PSR-16 cache, or false. See Choosing the cache.
cacheTtl · retryInterval30.0 · 5.0Seconds before a cached bundle is revalidated, and between attempts while the edge fails.
refreshtruefalse: never fetch, only read the cache (with the sync daemon).
offlinefalseNo network at all: bootstrap and cache only, no telemetry.
timeout3.0Seconds for a bundle request.
bootstrapnoneA bundle (JSON text or decoded array) used when nothing better is available.
verifyon for the hosted edgetrue, false or ['publicKeys' => …, 'require' => …, 'fetchKeys' => …].
events10 % sampledfalse or ['sampleRate', 'flushInterval', 'reportInterval', 'timeout', 'redact'].
http · requestFactory · streamFactorycurl or streamsA PSR-18 client with PSR-17 factories.
logger · onErrornoneA PSR-3 logger, and an error listener registered before the first load.
MethodDescription
boolVariation · stringVariation · numberVariation · jsonVariationTyped value: ($key, $default, $context = null).
*VariationDetail · evaluateAn EvaluationDetail.
allFlags · allFlagsDetailEvery 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

  1. Every variation returns the default. Check status() and lastError(). unauthorized means the key was rejected; with a browser key (nf_pub_…) only client-exposed flags are delivered.
  2. Every request fetches from the edge. That is what cache: false does. Otherwise the cache cannot be read or written: look for errors with code store, and check that the directory (or the PSR-16 backend) is writable by the PHP user.
  3. 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.
  4. Errors with code config about sodium. Install ext-sodium or paragonie/sodium_compat; without one of them every signed bundle is refused.
  5. 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.
Other languages
Native server SDKs also exist for Python, Go, Java, .NET and Ruby. Other languages can read NanoFlags flags through an OpenFeature OFREP provider.