SDKs
PHP
Server-side decisions for Laravel, Symfony and WordPress, with a shared datafile cache and events sent after the response.
liftcanary/liftcanary decides on your PHP server: Laravel, Symfony, WordPress, plain PHP-FPM, queue workers and CLI scripts. Decisions run locally from a datafile that every request shares through a cache, and events are sent after the response has gone to the visitor. A user gets the same variation as on the website, in the app and in the Node and Python SDKs.
Install#
composer require liftcanary/liftcanaryPHP 8.1 or newer (64-bit) with json and mbstring. No dependencies: it uses curl when it's loaded, PHP's streams otherwise, and APCu when it's enabled.
Usage#
Create one client per request (or one per worker in long-running processes) and reuse it. Creating it costs nothing: there's no network until the first decision.
// config/services.php: 'liftcanary' => ['key' => env('LIFTCANARY_SDK_KEY')]
$this->app->singleton(\LiftCanary\Client::class, fn () => new \LiftCanary\Client(config('services.liftcanary.key'), [
'cache' => new \LiftCanary\Cache\Psr16Cache(\Illuminate\Support\Facades\Cache::store()),
'logger' => \Illuminate\Support\Facades\Log::channel(),
]));public function store(Request $request, Client $liftcanary)
{
$user = $liftcanary->createUser(
(string) $request->user()->id,
['plan' => $request->user()->plan, 'country' => $request->header('CF-IPCountry')],
);
$flow = $user->getVariable('new_checkout', 'flow', 'classic');
$order = $this->placeOrder($request, $flow);
$user->track('purchase', value: $order->total, properties: ['currency' => $order->currency]);
return response()->json($order);
}In Symfony, register LiftCanary\Client as a service with $sdkKey: '%env(LIFTCANARY_SDK_KEY)%' and autowire it the same way. Without a framework, new Client(getenv('LIFTCANARY_SDK_KEY')) at the start of the request is enough.
The user#
| Method | Returns |
|---|---|
isEnabled($flag) | Whether the feature is on for this user. |
getVariable($flag, $name, $fallback) | The variable's value, or the fallback when the flag or variable is missing, null or of another kind. |
getString · getBool · getNumber · getJson | The same, with a typed fallback and result. |
decide($flag, sendExposure: true) | A Decision: flagKey, enabled, variationKey, ruleKey, inExperiment, reason, variables, revision. |
decideAll() | Decisions for every flag, by key. |
track($event, value: null, properties: []) | Records a goal event. value is summed or averaged by goals (revenue, latency). |
createUser($id, $attributes, bucketingId: null, page: null, activeLocations: [], anonymousId: null) takes the same fields as the other SDKs. Attributes are sent with events; page (the full request URL, for location conditions) and activeLocations never are. bucketingId hashes on another id, such as a company id to keep a whole account in one variation. Experiment exposures are logged automatically, once per user, flag, rule and variation.
Signing in#
The website snippet keeps a visitor's anonymous id in the liftcanary_anon cookie. Pass it as anonymousId when they sign in, so results count the landing-page visit and the signed-in user as one person (see From landing page to app); a missing or tampered cookie is ignored. To also keep the variation they saw before signing in, pass the same value as bucketingId. The browser sets the cookie unencrypted, so in Laravel read it from $_COOKIE (or exclude it from cookie encryption). On WordPress, use wp:<user id> as the id, like the plugin does.
$liftcanary->createUser((string) $user->id, anonymousId: $_COOKIE[Client::ANONYMOUS_ID_COOKIE] ?? null); // 'liftcanary_anon'Options#
The second argument of new Client($sdkKey, [...]), or an Options object (new Options(cacheTtl: 60)).
sdkKeyrequiredstring | The first argument: the environment's public SDK key (pk_…). |
datafilenull | A datafile (array or JSON) to start from: used until a newer one is loaded, and whenever none can be. |
offlinefalse | Never download; decide with datafile and setDatafile() only (tests, air-gapped servers). |
cdnUrlstring | Where datafiles come from. Default https://cdn.liftcanary.com; use your own domain or the API when self-hosting. |
eventsUrlstring | The collector. Default https://events.liftcanary.com. |
cacheAPCu, else file | A DatafileCache: new ApcuCache(), new FileCache($dir), new Psr16Cache($psr16) (Redis, Memcached, Laravel's Cache::store()), or false for this process only. |
cacheTtl30 | Seconds a cached datafile is used before it's revalidated. 0: on every request, with a 304 when unchanged. |
cacheMaxStale604800 | Seconds a stale copy may still be served while the CDN can't be reached (7 days). |
datafileTimeout2.0 | Seconds to wait for the CDN when revalidating. |
eventBatchSize200 | Events per request to the collector. |
eventMaxQueueSize10000 | Events kept in memory before the oldest are dropped (counted in events()->dropped()). |
eventTimeout5.0 | Seconds to wait for the collector. |
eventRetryDelay0.5 | Seconds before the one retry of a failed batch (with jitter). |
flushWhenFullCLI only | Send a batch as soon as eventBatchSize events are queued. |
flushOnShutdowntrue | Send what's queued when the request ends. |
finishRequesttrue | Finish the HTTP response before sending (PHP-FPM, LiteSpeed). |
disableEventsfalse | Decide without sending anything. |
transportcurl / streams | A LiftCanary\Http\Transport: wrap Guzzle or a PSR-18 client in a few lines; tests use a fake. |
loggersilent | A PSR-3 logger, or fn (string $level, string $message, array $context). |
modelPrices[] | Price per 1M tokens per model, for AI configs. |
How the datafile is cached#
- One copy for every request. PHP forgets everything between requests, so there are no background threads. With APCu, the datafile sits in shared memory for every PHP-FPM worker of the pool; otherwise it's a JSON file in a private directory under
sys_get_temp_dir(). - Revalidation. Once the cached copy is older than
cacheTtl, the next request checks it with the CDN (If-None-Match, a 304 when unchanged) while other requests keep using it, so a published change reaches your servers in about 30 seconds. - Outages. When the CDN can't be reached, the stale copy is served for up to 7 days and the next attempt waits 5 s, so an outage never slows every page view. Before any datafile is available every flag is off and the reason is
NOT_READY. Errors never throw into your app. - Events after the response. Exposures,
track()calls and sign-in links are sent in batches when the request ends. Under PHP-FPM and LiteSpeed the response is finished first (fastcgi_finish_request()), so visitors never wait for the collector. A 429, a 5xx or a network error gets one retry. - Long-running processes (Octane, RoadRunner, Swoole, queue workers): keep one client per worker and call
$client->flush()at the end of each request or job, because the process doesn't end.
AI configs#
Test models, prompts and parameters on real users, measured on latency, tokens, cost, errors and feedback. Your code still calls the provider.
use LiftCanary\AI;
$cfg = AI::config($user, 'support_bot', model: 'my-small-model', prompt: 'You are a helpful assistant.');
$reply = AI::measureLLM(
$user,
$cfg,
fn () => $llm->chat($cfg->model, AI::renderPrompt($cfg->prompt, ['language' => 'Turkish']), $cfg->params),
usage: fn ($r) => ['input_tokens' => $r->usage->inputTokens, 'output_tokens' => $r->usage->outputTokens],
);
AI::trackFeedback($user, $cfg, positive: true); // when the user rates the answerCosts need modelPrices on the client. AI::measureLLMStream() also records the time to first token of a streamed answer, and AI::trackLLM() a call you measured yourself. Prompts and answers are never sent. See AI configs and LLM experiments.