# A/B Smartly PHP SDK A/B Smartly - PHP SDK ## Compatibility 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. ### Upgrading from 1.0.x 1.1.0 retains the 1.0.3 entry class and legacy method signatures, including subclass overrides. It also changes runtime behavior, including experiment bucketing, exposure payloads and error handling. Review [CHANGELOG.md](CHANGELOG.md) before upgrading; existing workloads may behave differently. ## Installation A/B Smartly PHP SDK can be installed with [`composer`](https://getcomposer.org): ```bash composer require absmartly/php-sdk:^1.1 ``` ## Getting Started Please follow the [installation](#installation) instructions before trying the following code. ### Initialization This example assumes an API Key, an Application, and an Environment have been created in the A/B Smartly web console. #### Recommended: Simple API Once the SDK is installed, it can be initialized in your project using the simple API: ```php use ABSmartly\SDK\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: ```php use ABSmartly\SDK\SDK; $sdk = SDK::createWithDefaults( $endpoint, $apiKey, $environment, $application ); ``` #### Alternative: Manual Client Configuration 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: ```php use ABSmartly\SDK\Client\ClientConfig; use ABSmartly\SDK\Client\Client; use ABSmartly\SDK\Config; use ABSmartly\SDK\SDK; $clientConfig = new ClientConfig($endpoint, $apiKey, $application, $environment); $client = new Client($clientConfig); $config = new Config($client); $sdk = new SDK($config); ``` #### Using Async HTTP Client 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: ```bash 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`. ```php use ABSmartly\SDK\Client\ClientConfig; use ABSmartly\SDK\Client\Client; use ABSmartly\SDK\Http\ReactHttpClient; use ABSmartly\SDK\Config; use ABSmartly\SDK\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 when `HTTPClient::$totalTimeout` is set (retries are off otherwise, as in 1.0.x). 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](#custom-event-logger) below. | | `contextDataProvider` | `ContextDataProvider` | ❌ | auto | Custom provider for context data (advanced usage) | | `contextEventHandler` | `ContextEventHandler` | ❌ | auto | Custom handler for publishing events (advanced usage) | ## Creating a New Context ### Synchronously ```php use ABSmartly\SDK\Context\ContextConfig; $contextConfig = new ContextConfig(); $contextConfig->setUnit('session_id', '5ebf06d8cb5d8137290c4abb64155584fbdb64d8'); $context = $sdk->createContext($contextConfig); ``` ### Asynchronously (with ReactPHP) When using the async HTTP client, context creation is non-blocking: ```php 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()); } ); ``` ### With Pre-fetched Data 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. ```php 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()); ``` ### Refreshing the Context with Fresh Experiment Data 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`: ```php $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. After an initial load failure it can fetch and apply data, but `isFailed()` remains true, as in 1.0.3, and a failed context drops queued events on flush. Create a new context for full recovery. ### Setting Extra Units 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. ```php $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()` and `Context->setUnits()` methods can be called before the context is ready. ## Basic Usage ### Selecting a Treatment ```php $treatment = $context->getTreatment('exp_test_experiment'); if ($treatment === 0) { // user is in control group (variant 0) } else { // user is in treatment group } ``` ### Treatment Variables ```php $defaultButtonColorValue = 'red'; $buttonColor = $context->getVariableValue('button.color', $defaultButtonColorValue); ``` ### Peek at Treatment Variants 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. ```php $treatment = $context->peekTreatment('exp_test_experiment'); if ($treatment === 0) { // user is in control group (variant 0) } else { // user is in treatment group } ``` #### Peeking at Variables ```php $buttonColor = $context->peekVariableValue('button.color', 'red'); ``` ### Overriding Treatment Variants 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. ```php $context->setOverride('exp_test_experiment', 1); // force variant 1 of treatment $context->setOverrides([ 'exp_test_experiment' => 1, 'exp_another_experiment' => 0, ]); ``` ## Advanced ### Context Attributes 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. ```php $context->setAttribute('user_agent', $_SERVER['HTTP_USER_AGENT']); $context->setAttributes([ 'customer_age' => 'new_customer', 'session_id' => session_id() ]); ``` `setAttribute()` retains its string parameter, as in 1.0.3. To preserve numeric, boolean, object or other values for evaluation and publication, use `setAttributeValue('age', 25)` or `setAttributeValues([...])`. Attributes set on a `ContextConfig` are converted to strings, as in 1.0.3. 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. ### Assignment Rules 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): - `assign` rules pick a fixed variant. - `split` rules split traffic with their own percentages, such as `20/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. ### Semantic Version Conditions 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. ```php $context->setAttribute('app_version', '2.4.1'); ``` ### Client Metadata Every request sends the SDK name and version in the `X-Agent` header (`absmartly-php-sdk/`), 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`: ```php $clientConfig = new ClientConfig($endpoint, $apiKey, $application, $environment); $clientConfig->setApplicationVersion('1042'); ``` ### Custom Assignments 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. ```php $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. ```php $assignments = [ 'experiment_name' => 1, 'another_experiment_name' => 0, 'a_third_experiment_name' => 2 ]; $context->setCustomAssignments($assignments); ``` ### Tracking Goals Goals are created in the A/B Smartly Web Console. ```php $context->track('payment', (object) [ 'item_count' => 1, 'total_amount' => 1999.99 ]); ``` For an associative array of goal properties, use `trackWithProperties('payment', ['total_amount' => 1999.99])`. The original `track()` continues to accept an object or null. ### Publishing Pending Data 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. ```php $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). ### Finalizing The `close()` method will ensure all events have been published to the A/B Smartly collector, like `Context->publish()`, and closes the context. Event-generating operations such as `track()` and `getTreatment()` then throw; attribute and unit setters remain usable as in 1.0.3. ```php $context->close(); ``` ### Custom Event Logger 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`. #### Simple Callback Approach ```php 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)); } } )); ``` #### Interface Implementation Approach Alternatively, you can implement the `ContextEventLogger` interface with a `handleEvent()` method that receives the `Context` object itself, along with a `ContextEventLoggerEvent` object: ```php 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` | ## Platform-Specific Examples ### Using with Laravel Laravel applications can integrate A/B Smartly using service providers and middleware for request-scoped context management. ```php // 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 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 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 attributes->get('absmartly_context'); $treatment = $context->getTreatment('exp_product_layout'); if ($treatment === 0) { return view('product.show_control'); } else { return view('product.show_treatment'); } } } ``` ### Using with Symfony Symfony applications can integrate A/B Smartly using dependency injection and event subscribers for request lifecycle management. ```php // config/services.yaml services: ABSmartly\SDK\SDK: factory: ['ABSmartly\SDK\SDK', 'createWithDefaults'] arguments: $endpoint: '%env(ABSMARTLY_ENDPOINT)%' $apiKey: '%env(ABSMARTLY_API_KEY)%' $environment: '%env(APP_ENV)%' $application: 'website' // src/EventSubscriber/ABSmartlySubscriber.php 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 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'); } } } ``` ## Advanced Request Configuration ### Request Timeout Override PHP supports per-request timeout configuration through HTTP client options: ```php use ABSmartly\SDK\Client\ClientConfig; use ABSmartly\SDK\Client\Client; use ABSmartly\SDK\Http\HTTPClient; use ABSmartly\SDK\Config; use ABSmartly\SDK\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); ``` ### Async Request with ReactPHP For non-blocking operations with cancellation support: ```php use ABSmartly\SDK\Client\ClientConfig; use ABSmartly\SDK\Client\Client; use ABSmartly\SDK\Http\ReactHttpClient; use ABSmartly\SDK\Config; use ABSmartly\SDK\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"; } ); ``` ## Releasing The package is published on [Packagist](https://packagist.org/packages/absmartly/php-sdk), which picks up new tags through its GitHub webhook. To release: 1. Set `Client::SDK_VERSION` (sent in the `X-Agent` header) to the new version and move the [CHANGELOG.md](CHANGELOG.md) entries under it. 2. Merge to `main`. Packagist imports a tag as soon as it is pushed, so check the version on the merged `main` before tagging and push the tag only if the check passes: `php .github/scripts/check-release-version.php v1.1.0 && git tag v1.1.0 && git push origin v1.1.0`. 3. The Release workflow validates `composer.json`, re-checks that the tag matches `Client::SDK_VERSION`, runs the tests and creates the GitHub release; Packagist lists the version within a few minutes. ## About A/B Smartly **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. ### Have a look at our growing list of clients and SDKs: - [JavaScript SDK](https://www.github.com/absmartly/javascript-sdk) - [Java SDK](https://www.github.com/absmartly/java-sdk) - [PHP SDK](https://www.github.com/absmartly/php-sdk) (this package) - [Swift SDK](https://www.github.com/absmartly/swift-sdk) - [Vue2 SDK](https://www.github.com/absmartly/vue2-sdk) - [Vue3 SDK](https://www.github.com/absmartly/vue3-sdk) - [React SDK](https://www.github.com/absmartly/react-sdk) - [Python3 SDK](https://www.github.com/absmartly/python3-sdk) - [Go SDK](https://www.github.com/absmartly/go-sdk) - [Ruby SDK](https://www.github.com/absmartly/ruby-sdk) - [.NET SDK](https://www.github.com/absmartly/dotnet-sdk) - [Dart SDK](https://www.github.com/absmartly/dart-sdk) - [Flutter SDK](https://www.github.com/absmartly/flutter-sdk) See [CHANGELOG.md](CHANGELOG.md) for release notes.