A/B Smartly - PHP SDK
The A/B Smartly PHP SDK is compatible with PHP versions 7.4 and later. For the best performance and code readability, PHP 8.1 or later is recommended. This SDK is being constantly tested with the nightly builds of PHP to ensure it is compatible with the latest PHP version.
The SDK entry class is now ABSmartly\SDK. The previous fully qualified name, ABSmartly\SDK\SDK, is still available as an alias, so existing code keeps working without changes.
Traffic eligibility now uses the experiment's traffic seed, as in the other SDKs, which re-buckets running experiments whose traffic split is below 100%. audienceStrict: false is now honoured, and audience operators return null for null operands (see the CHANGELOG). Restart or start a new iteration of affected experiments when upgrading.
Everything else keeps its 1.x behaviour: units are stored as strings, track() accepts any object, publish() logs collector failures instead of throwing (the events stay queued for retry), a failed close() throws and leaves the context open so it can be retried, close() emits Close once it succeeds, refresh() on a context whose initial load failed is a no-op that stays failed (matching the JS SDK) — create a new context to recover — and error messages are unchanged. The legacy ABSmartly\SDK\SDK name, factory parameter ordering, ContextEventHandler contracts, and PublishEvent::hashUnit(string) override signature remain supported. ReactPHP is optional for synchronous use. See CHANGELOG.md for the full migration notes and audience/custom-field corrections.
A/B Smartly PHP SDK can be installed with composer:
composer require absmartly/php-sdkPlease follow the installation instructions before trying the following code.
This example assumes an API Key, an Application, and an Environment have been created in the A/B Smartly web console.
Once the SDK is installed, it can be initialized in your project using the simple API:
use ABSmartly\SDK;
$sdk = SDK::createWithDefaults(
endpoint: $endpoint,
apiKey: $apiKey,
environment: $environment,
application: $application
);Note that the above example uses named parameters introduced in PHP 8.0. Although it is strongly recommended to use the latest PHP version, PHP 7.4 is supported as well. On PHP 7.4, parameters are only passed in their order, as named parameters are not supported.
Example for PHP 7.4:
use ABSmartly\SDK;
$sdk = SDK::createWithDefaults(
$endpoint, $apiKey, $environment, $application
);The above is a shortcut that creates an SDK instance quickly using default values. If you need to manually configure individual components, you can do so:
use ABSmartly\SDK\Client\ClientConfig;
use ABSmartly\SDK\Client\Client;
use ABSmartly\SDK\Config;
use ABSmartly\SDK;
$clientConfig = new ClientConfig($endpoint, $apiKey, $application, $environment);
$client = new Client($clientConfig);
$config = new Config($client);
$sdk = new SDK($config);For non-blocking operations, you can use the ReactPHP-based async HTTP client. ReactPHP is not required for synchronous SDK use. Install these optional dependencies before using ReactHttpClient or the async SDK methods:
composer require 'react/http:^1.9' 'react/async:^3.0 || ^4.0' 'react/promise:^3.0'Composer selects a compatible react/async version for your PHP runtime (v3 supports PHP 7.4/8.0; v4 requires PHP 8.1+). Even with a synchronous transport, methods such as createContextAsync() and createContextPending() return ReactPHP promises and require react/promise.
use ABSmartly\SDK\Client\ClientConfig;
use ABSmartly\SDK\Client\Client;
use ABSmartly\SDK\Http\ReactHttpClient;
use ABSmartly\SDK\Config;
use ABSmartly\SDK;
$clientConfig = new ClientConfig($endpoint, $apiKey, $application, $environment);
$reactHttpClient = new ReactHttpClient();
$reactHttpClient->timeout = 3000;
$reactHttpClient->retries = 5;
$client = new Client($clientConfig, $reactHttpClient);
$config = new Config($client);
$sdk = new SDK($config);The async HTTP client uses ReactPHP promises and allows for non-blocking I/O operations.
SDK Options
| Config | Type | Required? | Default | Description |
|---|---|---|---|---|
endpoint |
string |
✅ | null |
The URL to your API endpoint. Most commonly "your-company.absmartly.io" |
apiKey |
string |
✅ | null |
Your API key which can be found on the Web Console. |
environment |
string |
✅ | null |
The environment of the platform where the SDK is installed. Environments are created on the Web Console and should match the available environments in your infrastructure. |
application |
string |
✅ | null |
The name of the application where the SDK is installed. Applications are created on the Web Console and should match the applications where your experiments will be running. |
retries |
int |
❌ | 5 |
The number of times a failed GET request is retried. Event publishing (PUT) is never retried. |
timeout |
int |
❌ | 3000 |
An amount of time, in milliseconds, before the SDK will stop trying to connect. |
eventLogger |
ContextEventLogger |
❌ | null |
A callback function which runs after SDK events. See Custom Event Logger below. |
contextDataProvider |
ContextDataProvider |
❌ | auto | Custom provider for context data (advanced usage) |
contextEventHandler |
ContextEventHandler |
❌ | auto | Custom handler for publishing events (advanced usage) |
use ABSmartly\SDK\Context\ContextConfig;
$contextConfig = new ContextConfig();
$contextConfig->setUnit('session_id', '5ebf06d8cb5d8137290c4abb64155584fbdb64d8');
$context = $sdk->createContext($contextConfig);When using the async HTTP client, context creation is non-blocking:
use ABSmartly\SDK\Context\ContextConfig;
use React\Promise\PromiseInterface;
$contextConfig = new ContextConfig();
$contextConfig->setUnit('session_id', '5ebf06d8cb5d8137290c4abb64155584fbdb64d8');
$sdk->createContextAsync($contextConfig)->then(
function($context) {
$treatment = $context->getTreatment('exp_test_experiment');
},
function($error) {
error_log('Context failed: ' . $error->getMessage());
}
);When doing full-stack experimentation with A/B Smartly, we recommend creating a context only once on the server-side. Creating a context involves a round-trip to the A/B Smartly event collector. We can avoid repeating the round-trip on the client-side by re-using data previously retrieved.
use ABSmartly\SDK\Context\ContextConfig;
$contextConfig = new ContextConfig();
$contextConfig->setUnit('session_id', '5ebf06d8cb5d8137290c4abb64155584fbdb64d8');
$context = $sdk->createContext($contextConfig);
$anotherContextConfig = new ContextConfig();
$anotherContextConfig->setUnit('session_id', 'another-user-id');
$anotherContext = $sdk->createContextWithData($anotherContextConfig, $context->getContextData());For long-running contexts, the context is usually created once when the application is first started. However, any experiments being tracked in your production code, but started after the context was created, will not be triggered.
To mitigate this, we can use the Context->refresh() method on the Context:
$context->refresh();The Context->refresh() method pulls updated experiment data from the A/B Smartly collector and will trigger recently started experiments when Context->getTreatment() is called again.
You can add additional units to a context by calling the Context->setUnit() or Context->setUnits() methods. These methods may be used, for example, when a user logs in to your application, and you want to use the new unit type in the context.
$context->setUnit('user_id', 143432);
$context->setUnits([
'user_id' => 143432,
'db_user_id' => 1000013
]);Note: You cannot override an already set unit type as that would be a change of identity, and would throw an exception. In this case, you must create a new context instead. The
Context->setUnit()andContext->setUnits()methods can be called before the context is ready.
$treatment = $context->getTreatment('exp_test_experiment');
if ($treatment === 0) {
// user is in control group (variant 0)
} else {
// user is in treatment group
}$defaultButtonColorValue = 'red';
$buttonColor = $context->getVariableValue('button.color', $defaultButtonColorValue);Although generally not recommended, it is sometimes necessary to peek at a treatment or variable without triggering an exposure. The A/B Smartly SDK provides a Context->peekTreatment() method for that.
$treatment = $context->peekTreatment('exp_test_experiment');
if ($treatment === 0) {
// user is in control group (variant 0)
} else {
// user is in treatment group
}$buttonColor = $context->peekVariableValue('button.color', 'red');During development, for example, it is useful to force a treatment for an experiment. This can be achieved with the Context->setOverride() and/or Context->setOverrides() methods. These methods can be called before the context is ready.
$context->setOverride('exp_test_experiment', 1); // force variant 1 of treatment
$context->setOverrides([
'exp_test_experiment' => 1,
'exp_another_experiment' => 0,
]);Attributes are used to pass meta-data about the user and/or the request. They can be used later in the Web Console to create segments or audiences. They can be set using the Context->setAttribute() or Context->setAttributes() methods, before or after the context is ready.
$context->setAttribute('user_agent', $_SERVER['HTTP_USER_AGENT']);
$context->setAttributes([
'customer_age' => 'new_customer',
'session_id' => session_id()
]);The application and environment names configured on the client are always available to audience
filters as the application and environment attributes, without being set explicitly. A user
attribute of the same name, set with setAttribute(), overrides the configured value for audience
evaluation. An empty name is left out, and app_version is never added automatically: set it with
setAttribute() to target versions. These names are not added to the published attributes.
An experiment can carry assignment rules, configured in the Web Console. The first rule whose environments
and conditions match decides the variant, ahead of the audience, traffic split, full-on variant and custom
assignments (an override set with setOverride() still wins over every rule):
assignrules pick a fixed variant.splitrules split traffic with their own percentages, such as20/30/50, hashing the unit with the experiment's seed. A split that does not cover every variant, or does not sum to 100 (within 0.01), is ignored.
Rule conditions are audience expressions evaluated against the context attributes, including the application
and environment names. A rule's environments list is always matched against the environment configured on the
client, even when an environment attribute is set. They are re-evaluated when an attribute changes, so a cached assignment follows the rule
that matches now; an exposure that was already queued is not taken back. A split rule that matches before its unit
is set gives the full-on variant (variant 0 when the experiment is not full-on) until the unit is set, unless the
treatment was already exposed. Exposures decided by a rule are flagged ruleOverride and excluded from analysis.
Audience and rule conditions can compare versions with semver_eq, semver_gt, semver_gte, semver_lt and
semver_lte. A leading v and build metadata (+build.7) are ignored, missing parts count as 0 (1.2 equals
1.2.0), numeric parts compare as numbers (1.10.0 is greater than 1.9.0) and a release is greater than its
pre-releases (2.0.0 is greater than 2.0.0-rc.1). A value that is not a version makes the comparison null.
$context->setAttribute('app_version', '2.4.1');Every request sends the SDK name and version in the X-Agent header (absmartly-php-sdk/<version>), and the
application version in X-Application-Version. Set the application version on the client configuration; the
collector accepts whole numbers only, so other versions (such as 2.4.1) are sent as 0:
$clientConfig = new ClientConfig($endpoint, $apiKey, $application, $environment);
$clientConfig->setApplicationVersion('1042');Sometimes it may be necessary to override the automatic selection of a variant. For example, if you wish to have your variant chosen based on data from an API call. This can be accomplished using the Context->setCustomAssignment() method.
$chosenVariant = 1;
$context->setCustomAssignment('experiment_name', $chosenVariant);If you are running multiple experiments and need to choose different custom assignments for each one, you can do so using the Context->setCustomAssignments() method.
$assignments = [
'experiment_name' => 1,
'another_experiment_name' => 0,
'a_third_experiment_name' => 2
];
$context->setCustomAssignments($assignments);Goals are created in the A/B Smartly Web Console.
$context->track('payment', (object) [
'item_count' => 1,
'total_amount' => 1999.99
]);Sometimes it is necessary to ensure all events have been published to the A/B Smartly collector before proceeding. You can explicitly call the Context->publish() method.
$context->publish();If the collector cannot be reached, publish() does not throw: the error is logged (as an Error event when an event logger is set) and the events stay queued. A failed close() throws the publish error and leaves the context open with its events queued; calling close() again retries them, and Close is emitted only once a close succeeds. The retained queue is capped (oldest events are dropped with an Error log).
The close() method will ensure all events have been published to the A/B Smartly collector, like Context->publish(), and will also "seal" the context, throwing an error if any method that could generate an event is called.
$context->close();The A/B Smartly SDK can be instantiated with an event logger used for all contexts. In addition, an event logger can be specified when creating a particular context in the ContextConfig.
use ABSmartly\SDK\Context\ContextConfig;
use ABSmartly\SDK\Context\ContextEventLoggerCallback;
$contextConfig = new ContextConfig();
$contextConfig->setEventLogger(new ContextEventLoggerCallback(
function (string $event, ?object $data) {
if ($event === 'Error') {
error_log('ABSmartly Error: ' . print_r($data, true));
}
}
));Alternatively, you can implement the ContextEventLogger interface with a handleEvent() method that receives the Context object itself, along with a ContextEventLoggerEvent object:
use ABSmartly\SDK\Context\Context;
use ABSmartly\SDK\Context\ContextEventLogger;
use ABSmartly\SDK\Context\ContextEventLoggerEvent;
class CustomLogger implements ContextEventLogger {
public function handleEvent(Context $context, ContextEventLoggerEvent $event): void {
$eventName = $event->getEvent();
$eventData = $event->getData();
switch ($eventName) {
case 'Exposure':
break;
case 'Goal':
break;
case 'Error':
error_log('ABSmartly Error: ' . print_r($eventData, true));
break;
}
}
}
$contextConfig = new ContextConfig();
$contextConfig->setEventLogger(new CustomLogger());Event Types
The data parameter depends on the type of event. Currently, the SDK logs the following events:
| Event | When | Data |
|---|---|---|
Error |
Context receives an error |
Exception object thrown |
Ready |
Context turns ready |
ContextData object used to initialize the context |
Refresh |
Context->refresh() method succeeds |
ContextData used to refresh the context |
Publish |
Context->publish() method succeeds |
PublishEvent data sent to the A/B Smartly event collector |
Exposure |
Context->getTreatment() method succeeds on first exposure |
Exposure data enqueued for publishing |
Goal |
Context->track() method succeeds |
GoalAchievement goal data enqueued for publishing |
Close |
Context->close() method succeeds the first time |
null |
Laravel applications can integrate A/B Smartly using service providers and middleware for request-scoped context management.
// config/absmartly.php
return [
'endpoint' => env('ABSMARTLY_ENDPOINT'),
'api_key' => env('ABSMARTLY_API_KEY'),
'application' => env('ABSMARTLY_APPLICATION', 'website'),
'environment' => env('APP_ENV'),
];
// app/Providers/ABSmartlyServiceProvider.php
<?php
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
use ABSmartly\SDK;
class ABSmartlyServiceProvider extends ServiceProvider
{
public function register()
{
$this->app->singleton(SDK::class, function ($app) {
$config = config('absmartly');
return SDK::createWithDefaults(
endpoint: $config['endpoint'],
apiKey: $config['api_key'],
environment: $config['environment'],
application: $config['application']
);
});
}
}
// app/Http/Middleware/ABSmartlyContext.php
<?php
namespace App\Http\Middleware;
use Closure;
use ABSmartly\SDK;
use ABSmartly\SDK\Context\ContextConfig;
class ABSmartlyContext
{
protected $sdk;
public function __construct(SDK $sdk)
{
$this->sdk = $sdk;
}
public function handle($request, Closure $next)
{
$contextConfig = new ContextConfig();
$contextConfig->setUnit('session_id', $request->session()->getId());
if (auth()->check()) {
$contextConfig->setUnit('user_id', auth()->id());
}
$context = $this->sdk->createContext($contextConfig);
$request->attributes->set('absmartly_context', $context);
$response = $next($request);
$context->close();
return $response;
}
}
// app/Http/Controllers/ProductController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class ProductController extends Controller
{
public function show(Request $request)
{
$context = $request->attributes->get('absmartly_context');
$treatment = $context->getTreatment('exp_product_layout');
if ($treatment === 0) {
return view('product.show_control');
} else {
return view('product.show_treatment');
}
}
}Symfony applications can integrate A/B Smartly using dependency injection and event subscribers for request lifecycle management.
// config/services.yaml
services:
ABSmartly\SDK:
factory: ['ABSmartly\SDK', 'createWithDefaults']
arguments:
$endpoint: '%env(ABSMARTLY_ENDPOINT)%'
$apiKey: '%env(ABSMARTLY_API_KEY)%'
$environment: '%env(APP_ENV)%'
$application: 'website'
// src/EventSubscriber/ABSmartlySubscriber.php
<?php
namespace App\EventSubscriber;
use ABSmartly\SDK;
use ABSmartly\SDK\Context\ContextConfig;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\Event\RequestEvent;
use Symfony\Component\HttpKernel\Event\ResponseEvent;
use Symfony\Component\HttpKernel\KernelEvents;
class ABSmartlySubscriber implements EventSubscriberInterface
{
private $sdk;
private $context;
public function __construct(SDK $sdk)
{
$this->sdk = $sdk;
}
public static function getSubscribedEvents()
{
return [
KernelEvents::REQUEST => 'onKernelRequest',
KernelEvents::RESPONSE => 'onKernelResponse',
];
}
public function onKernelRequest(RequestEvent $event)
{
$request = $event->getRequest();
$session = $request->getSession();
$contextConfig = new ContextConfig();
$contextConfig->setUnit('session_id', $session->getId());
$this->context = $this->sdk->createContext($contextConfig);
$request->attributes->set('absmartly_context', $this->context);
}
public function onKernelResponse(ResponseEvent $event)
{
if ($this->context) {
$this->context->close();
}
}
}
// src/Controller/ProductController.php
<?php
namespace App\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
class ProductController extends AbstractController
{
public function show(Request $request): Response
{
$context = $request->attributes->get('absmartly_context');
$treatment = $context->getTreatment('exp_product_layout');
if ($treatment === 0) {
return $this->render('product/show_control.html.twig');
} else {
return $this->render('product/show_treatment.html.twig');
}
}
}PHP supports per-request timeout configuration through HTTP client options:
use ABSmartly\SDK\Client\ClientConfig;
use ABSmartly\SDK\Client\Client;
use ABSmartly\SDK\Http\HTTPClient;
use ABSmartly\SDK\Config;
use ABSmartly\SDK;
use ABSmartly\SDK\Context\ContextConfig;
$httpClient = new HTTPClient();
$clientConfig = new ClientConfig($endpoint, $apiKey, $application, $environment);
$clientConfig->setTimeout(1500);
$client = new Client($clientConfig, $httpClient);
$config = new Config($client);
$sdk = new SDK($config);
$contextConfig = new ContextConfig();
$contextConfig->setUnit('session_id', 'abc123');
$context = $sdk->createContext($contextConfig);For non-blocking operations with cancellation support:
use ABSmartly\SDK\Client\ClientConfig;
use ABSmartly\SDK\Client\Client;
use ABSmartly\SDK\Http\ReactHttpClient;
use ABSmartly\SDK\Config;
use ABSmartly\SDK;
use ABSmartly\SDK\Context\ContextConfig;
use React\EventLoop\Loop;
$reactHttpClient = new ReactHttpClient();
$reactHttpClient->timeout = 1500;
$clientConfig = new ClientConfig($endpoint, $apiKey, $application, $environment);
$client = new Client($clientConfig, $reactHttpClient);
$config = new Config($client);
$sdk = new SDK($config);
$contextConfig = new ContextConfig();
$contextConfig->setUnit('session_id', 'abc123');
$timeout = Loop::addTimer(1.5, function() {
echo "Context creation timed out\n";
});
$sdk->createContextAsync($contextConfig)->then(
function($ctx) use ($timeout) {
Loop::cancelTimer($timeout);
echo "Context ready!\n";
},
function($error) use ($timeout) {
Loop::cancelTimer($timeout);
echo "Context failed: " . $error->getMessage() . "\n";
}
);The package is published on Packagist, which picks up new tags through its GitHub webhook. To release:
- Set
Client::SDK_VERSION(sent in theX-Agentheader) to the new version and move the CHANGELOG.md entries under it. - Merge to
main. Packagist imports a tag as soon as it is pushed, so check the version on the mergedmainbefore tagging and push the tag only if the check passes:php .github/scripts/check-release-version.php v2.0.0 && git tag v2.0.0 && git push origin v2.0.0. - The Release workflow validates
composer.json, re-checks that the tag matchesClient::SDK_VERSION, runs the tests and creates the GitHub release; Packagist lists the version within a few minutes.
A/B Smartly is the leading provider of state-of-the-art, on-premises, full-stack experimentation platforms for engineering and product teams that want to confidently deploy features as fast as they can develop them. A/B Smartly's real-time analytics helps engineering and product teams ensure that new features will improve the customer experience without breaking or degrading performance and/or business metrics.
- JavaScript SDK
- Java SDK
- PHP SDK (this package)
- Swift SDK
- Vue2 SDK
- Vue3 SDK
- React SDK
- Python3 SDK
- Go SDK
- Ruby SDK
- .NET SDK
- Dart SDK
- Flutter SDK
See CHANGELOG.md for release notes.