reflag / sdk
PHP and Laravel server SDK for Reflag feature flags
Requires
- php: ^8.2
- ext-json: *
- guzzlehttp/guzzle: ^7.8
- psr/clock: ^1.0
- psr/http-client: ^1.0
- psr/http-message: ^1.1 || ^2.0
- psr/log: ^2.0 || ^3.0
- psr/simple-cache: ^2.0 || ^3.0
Requires (Dev)
- orchestra/testbench: ^9.0 || ^10.0 || ^11.0
- phpstan/phpstan: ^2.1
- phpunit/phpunit: ^11.0 || ^12.0
- predis/predis: ^2.2 || ^3.0
Suggests
- ext-redis: Redis fallback provider using phpredis
- aws/aws-sdk-php: S3 fallback provider
- google/cloud-storage: Google Cloud Storage fallback provider
- illuminate/support: Laravel integration (service provider, facade, Blade directives, commands)
- predis/predis: Redis fallback provider using Predis
Provides
None
Conflicts
None
Replaces
None
README
PHP and Laravel server SDK for Reflag feature flags.
- Flags are evaluated locally against cached definitions: reading a flag never calls Reflag.
- Definitions are shared between requests and workers through your cache and revalidated in the background, after the response has been sent.
- Boolean and multivariate (JSON-valued) flags, targeting rules, segments, flag dependencies and percentage rollouts.
- Laravel: auto-discovered service provider,
Reflagfacade, the signed-in user as default context, Blade directives, route middleware, a testing fake, andreflag:*Artisan commands. - Works without Laravel too (PSR-16 cache, PSR-18 HTTP, PSR-3 logging).
Requires PHP 8.2+. The Laravel integration supports Laravel 12 and 13 (see Laravel versions).
Installation
composer require reflag/sdk
Set your environment's secret key:
REFLAG_SECRET_KEY=your-secret-key
The service provider and Reflag facade are registered automatically. Publish the config if you want to change the defaults:
php artisan vendor:publish --tag=reflag-config
Not using Laravel? See Plain PHP.
Reading flags
Reads without an explicit context use the signed-in user:
use Reflag\Laravel\Facades\Reflag; if (Reflag::getFlag('new-dashboard')) { // … } $theme = Reflag::getFlag('theme', 'light'); // string flag, default 'light' $limit = Reflag::getFlag('upload-limit-mb', 10); // number flag $model = Reflag::getFlag('model-config', ['name' => 'small']); // JSON object flag
Pass a model, an array or a ReflagContext to evaluate for someone else, and bind it when you read several flags:
$reflag = Reflag::for($user, $company); $reflag->getFlag('beta-search'); $reflag->getFlag('model-config', null); // any JSON value Reflag::getFlag('beta-search', context: [ 'user' => ['id' => 'user-123', 'email' => 'ada@example.com', 'role' => 'admin'], 'company' => ['id' => 'acme', 'plan' => 'enterprise'], 'other' => ['region' => 'eu'], ]);
You can also inject Reflag\ReflagClient, the class behind the facade, into controllers, jobs and services.
Flag types
getFlag is the only read method. The default you pass selects the JSON type you expect:
| Call | Returns |
|---|---|
getFlag('x') |
true only for a resolved true; anything else is false |
getFlag('x', 'light') |
a string, or the default |
getFlag('x', 10) |
an int or float, or the default |
getFlag('x', ['a' => 1]) |
an associative array (JSON object), or the default |
getFlag('x', ['a', 'b']) |
a list (JSON array), or the default |
getFlag('x', null) |
any JSON value, including null |
When a flag has no value or its value has a different type, you get the default and a warning is logged. Values are never coerced: "false" is not false, and 1 is not true. Falsy values such as 0, "" and [] are returned as they are.
PHP arrays can't tell an empty JSON object from an empty list, so getFlag returns both {} and [] as []. Bootstrap payloads and fallback snapshots keep {} intact.
getFlags() returns every flag's value (null when a flag has none) and registers a check for each one.
What Reflag sees about your users
By default the user's id, name and email are sent, with no company. To control this, implement ProvidesReflagContext on your models:
use Reflag\Contracts\ProvidesReflagContext; class User extends Authenticatable implements ProvidesReflagContext { public function toReflagContext(): array { return [ 'user' => ['id' => $this->id, 'name' => $this->name, 'email' => $this->email, 'role' => $this->role], 'company' => ['id' => $this->company_id, 'name' => $this->company->name, 'plan' => $this->company->plan], ]; } }
A Reflag company is whatever your app groups users into: a team, account, workspace or organization. Instead of implementing the interface, you can set context.company in config/reflag.php to a relation or attribute, for example 'currentTeam' in a Jetstream app. You can also replace the resolver with your own Reflag\Contracts\ContextResolver.
Attribute names are case-sensitive. Nested arrays are flattened for targeting (for example company.address.country), and lists work with the ANY_OF, CONTAINS, IS and SET operators.
Blade
@flag('new-dashboard') <x-new-dashboard /> @elseflag('beta-dashboard') <x-beta-dashboard /> @else <x-dashboard /> @endflag @unlessflag('maintenance-banner-hidden') <x-banner /> @endflag
Routes
The reflag middleware responds with a 404 unless every listed flag is enabled for the signed-in user:
use Reflag\Laravel\Middleware\EnsureFlagsAreEnabled; Route::get('/dashboard/new', NewDashboardController::class)->middleware(['auth', 'reflag:new-dashboard']); Route::middleware(['auth', EnsureFlagsAreEnabled::using('beta-search', 'search-v2')])->group(function () { // … });
Put it after auth so the signed-in user is known. Only a flag that resolves to true lets the request through.
Front end
Hand flags to a v2 browser SDK (Browser, React, Vue) so it renders without fetching them first. With Blade:
<script> window.reflagBootstrap = @reflagBootstrap; </script>
With Inertia, share them as a prop:
// app/Http/Middleware/HandleInertiaRequests.php public function share(Request $request): array { return [ ...parent::share($request), 'reflag' => fn () => Reflag::getFlagsForBootstrap(), ]; }
<ReflagBootstrappedProvider publishableKey="pub_…" flags={usePage().props.reflag}>
@reflagBootstrap and getFlagsForBootstrap() accept an optional context. Only flags marked as client-visible are included, and generating the payload doesn't register flag checks. The payload includes the full context, so every attribute in it is visible in the browser; bootstrap with a context that contains only what the browser may see.
Keeping definitions fresh
Definitions are stored in your cache (REFLAG_CACHE_STORE, defaulting to the default store). A request serves whatever is cached. When the copy is older than refresh_interval (60 seconds), one process revalidates it with a conditional request after its response has been sent. Only a completely empty cache makes a request wait, and then just one process fetches while the others wait for it, up to cold_start_wait.
Two optional additions make updates faster and keep request handlers from ever refreshing. First, schedule a refresh and a telemetry flush:
// routes/console.php use Illuminate\Support\Facades\Schedule; Schedule::command('reflag:refresh')->everyMinute()->onOneServer(); Schedule::command('reflag:flush')->everyMinute()->onOneServer();
For updates within seconds, also run the push listener. It refreshes the cache as soon as flags change, reconnects automatically, and sends buffered telemetry. Run it under Supervisor, like a queue worker:
[program:reflag-listen] command=php /var/www/app/artisan reflag:listen autostart=true autorestart=true stopwaitsecs=30 user=forge redirect_stderr=true stdout_logfile=/var/www/app/storage/logs/reflag-listen.log
On SIGTERM the listener sends any buffered telemetry and exits. Restart it after each deployment (supervisorctl restart reflag-listen) so it runs your new code.
Artisan commands
| Command | Purpose |
|---|---|
reflag:refresh |
Fetch the latest definitions into the cache. In deploy scripts, --wait-for-version=N waits until Reflag has published that flag state version. |
reflag:flush |
Send buffered telemetry. |
reflag:listen |
Keep definitions up to date through push updates. --max-time=N stops after N seconds; --no-drain leaves telemetry to reflag:flush. |
Telemetry
Flag checks and user and company attributes are queued during the request and sent after the response. With a Redis, Memcached, database or DynamoDB cache, the SDK buffers batches from many requests in the cache and sends them together. This happens through reflag:flush, reflag:listen, or opportunistically every 10 seconds. With other stores, or REFLAG_TELEMETRY_DRIVER=request, each request sends its own batch.
Identical events are deduplicated across requests for 60 seconds, so checking the same flag on every page view does not send the same event every time.
Reflag::updateUser($user->id, ['plan' => 'pro']); Reflag::updateCompany($company->id, ['seats' => 25], userId: $user->id);
Queue workers flush after every job; Octane flushes after every request.
php artisan serve can't send a response before PHP finishes, so locally each page also waits for telemetry and any background refresh. PHP-FPM (including Herd and Valet), Octane and queue workers don't have this delay.
Turning off telemetry
Leave telemetry on for normal traffic. Turn it off when you evaluate flags on someone's behalf without recording that activity, for example in support impersonation or internal previews:
$reflag = Reflag::for($customer, telemetry: false); $reflag->getFlag('new-dashboard'); // no check, no attribute sync
Calling updateUser or updateCompany on the client itself always sends. Pass active: false to update attributes without changing Last seen.
Testing
Reflag::fake() replaces the client with one that makes no network calls and records flag checks and attribute updates:
use App\Models\User; use Reflag\Laravel\Facades\Reflag; it('shows the new dashboard', function () { Reflag::fake(['new-dashboard' => true, 'theme' => 'dark']); $user = User::factory()->create(); $this->actingAs($user)->get('/dashboard')->assertOk(); Reflag::assertFlagChecked('new-dashboard'); Reflag::assertFlagNotChecked('old-dashboard'); Reflag::assertUserUpdated($user->id); // or assertCompanyUpdated($id) });
Values can also come from a closure that receives the ReflagContext:
use Reflag\ReflagContext; Reflag::fake(fn (ReflagContext $context) => ['beta' => $context->companyId() === 'acme']);
The fake ignores REFLAG_FLAGS_ENABLED and REFLAG_FLAGS_DISABLED, so tests see only the flags they pass.
Overrides
Overrides replace evaluated values locally. They're useful in development and demos.
REFLAG_FLAGS_ENABLED=new-dashboard,beta-search REFLAG_FLAGS_DISABLED=legacy-export
// config/reflag.php 'overrides' => ['theme' => 'dark', 'model' => ['name' => 'small']],
use Reflag\ReflagContext; Reflag::setFlagOverrides(fn (ReflagContext $context) => ['beta' => $context->companyId() === 'qa']); Reflag::withFlagOverrides(['beta' => false], function () { // only inside this callback }); Reflag::clearFlagOverrides();
The config/reflag.php overrides win over the environment lists. setFlagOverrides() and clearFlagOverrides() replace both.
Overrides apply after evaluation, so overriding a flag doesn't change other flags that depend on it.
Fallback
If the cache is empty and Reflag can't be reached (for example, a fresh deployment during an outage), the SDK can start from a fallback. Once it has definitions it keeps serving them through later outages, with no fallback needed.
REFLAG_FALLBACK_DRIVER=disk # static, file, disk, redis, s3, gcs, azure, or a class name REFLAG_FALLBACK_DISK=s3
| Driver | Configuration | Requires |
|---|---|---|
static |
fallback.flags: fixed values |
|
file |
fallback.directory (default storage/reflag) |
|
disk |
fallback.disk: any Laravel filesystem disk |
|
redis |
fallback.connection |
phpredis or Predis |
s3 |
fallback.bucket; an Aws\S3\S3Client from the container |
aws/aws-sdk-php |
gcs |
fallback.bucket; a StorageClient from the container |
google/cloud-storage |
azure |
fallback.azure_sas_url: a container SAS URL |
Every live update is saved to the fallback. Static values don't identify authored variants, so checks against them are reported as unresolved.
The file and redis providers use flagStateVersion to prevent older snapshots from replacing newer ones. The Redis provider needs EVAL, GET, and SET permissions. Use a phpredis connection with serialization and compression disabled so the script can read the stored JSON. Custom clients must expose get and a Predis-compatible eval.
Offline mode
REFLAG_OFFLINE=true turns off all network I/O: reads return defaults and overrides, nothing is fetched or loaded from a fallback, and no telemetry is sent.
Configuration
config/reflag.php |
Env | ReflagOptions (plain PHP) |
Default |
|---|---|---|---|
secret_key |
REFLAG_SECRET_KEY |
secretKey |
required unless offline |
api_base_url |
REFLAG_API_BASE_URL |
apiBaseUrl |
https://front.reflag.com |
push_url |
REFLAG_PUSH_URL |
pushUrl |
{api_base_url}/sse/server |
offline |
REFLAG_OFFLINE |
offline |
false |
cache_store |
REFLAG_CACHE_STORE |
store |
default cache store |
telemetry_driver |
REFLAG_TELEMETRY_DRIVER |
telemetryDriver |
auto |
refresh_interval |
refreshInterval |
60 seconds |
|
cold_start_wait |
coldStartWait |
5 seconds |
|
fetch_timeout |
fetchTimeout |
10 seconds |
|
fetch_retries |
fetchRetries |
3 (scheduled and pushed refreshes) |
|
flush_interval |
flushInterval |
10 seconds |
|
batch_size |
batchSize |
100 |
|
overrides |
REFLAG_FLAGS_ENABLED, REFLAG_FLAGS_DISABLED |
flagOverrides |
none |
fallback.* |
REFLAG_FALLBACK_* |
fallbackProvider |
none |
log_channel |
REFLAG_LOG_CHANNEL |
logger |
default channel |
To customize HTTP (proxies, TLS), bind a PSR-18 client as reflag.http_client in a service provider.
Failed evaluations
If a targeting rule can't be evaluated, for example because a required context field is missing or has the wrong type, that rule is treated as not matching. A rate-limited warning is logged and the failure is reported to Reflag, where you can see it under failed evaluations. Warnings never include context values.
Laravel versions
The SDK itself doesn't depend on Laravel. The integration is tested on Laravel 12 and 13. It also runs on Laravel 11, but every Laravel 11 release has unpatched security advisories, so we recommend upgrading.
Remote config
Remote config isn't supported. Use multivariate flags for configuration values.
Plain PHP
use Reflag\ReflagClient; use Reflag\ReflagOptions; use Reflag\Store\Psr16Store; $reflag = new ReflagClient(new ReflagOptions( secretKey: getenv('REFLAG_SECRET_KEY'), store: new Psr16Store($cache), // any PSR-16 cache; omit in CLI scripts and long-running workers )); $enabled = $reflag->getFlag('new-dashboard', context: ['user' => ['id' => 'user-123'], 'company' => ['id' => 'acme']]); // At the end of the request or job (also runs when the client is destroyed): $reflag->terminate();
Without a store, definitions are kept in process memory. That suits CLI scripts, queue consumers and long-running servers (RoadRunner, Swoole, ReactPHP), but under PHP-FPM every request would fetch again, so give FPM applications a shared cache. A plain PSR-16 cache has no atomic operations, so telemetry is sent per request. For buffered telemetry, implement Reflag\Contracts\SharedStore over Redis.
ReflagOptions you don't pass are read from REFLAG_SECRET_KEY, REFLAG_API_BASE_URL, REFLAG_OFFLINE, REFLAG_FLAGS_ENABLED and REFLAG_FLAGS_DISABLED; options you pass win. Pass a PSR-18 client as httpClient to customize HTTP.
For fallbacks, use Reflag\Fallback\ReflagFallbackProviders::static(), ::file(), ::redis(), ::s3(), ::gcs() or ::azureBlob(), or implement FlagsFallbackProvider.
To push updates, run a small daemon:
(new Reflag\FlagUpdatesListener($reflag))->run();
Example app
examples/laravel-app is a tiny Laravel app with flag endpoints, Blade directives, browser bootstrap and Reflag::fake() tests. It runs offline without a secret key. examples/basic.php shows plain PHP.
License
MIT. See LICENSE.