Skip to content
absmartlyPublic

About

A/B Smartly php-sdk

Resources

Stars

2 stars

Watchers

2 watching

Forks

Latest commit

 

History

316 Commits

Folders and files

Repository files navigation

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 before upgrading; existing workloads may behave differently.

Installation

A/B Smartly PHP SDK can be installed with composer:

composer require absmartly/php-sdk:^1.2

Getting Started

Please follow the 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:

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:

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:

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:

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\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 below.
contextDataProvider ContextDataProvider ❌ auto Custom provider for context data (advanced usage). Return fresh ContextData, experiment and holdout objects on each call; never mutate ones already handed to a context.
contextEventHandler ContextEventHandler ❌ auto Custom handler for publishing events (advanced usage)

Creating a New Context

Synchronously

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:

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.

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:

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

$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

$treatment = $context->getTreatment('exp_test_experiment');

if ($treatment === 0) {
    // user is in control group (variant 0)
} else {
    // user is in treatment group
}

Treatment Variables

$defaultButtonColorValue = 'red';
$buttonColor = $context->getVariableValue('button.color', $defaultButtonColorValue);

Shared variable keys

When several experiments define the same variable key, the SDK picks one winner: among the experiments whose variants define the key, ordered by experiment id, the first one the user is assigned to, overridden into or rule-assigned to. A user outside the traffic split or failing a non-strict audience is still in the experiment and gets its value for their variant, and a full-on experiment counts even without the user's unit. A strict audience mismatch, or no unit for a non-full-on experiment's unit type, does not count unless an override or a matching assignment rule assigns the user. Only the winner is exposed. If the winner's variant does not define the key, or the user is in none of them, the default value is returned; a later experiment is never used instead.

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.

$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

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

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

$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 keep their value in the ContextConfig and are converted to strings when the context is created, as in 1.0.3: 25 becomes '25', while a value that cannot be converted (an array or object) raises a TypeError from createContext(). Use setAttributeValue() on the context for such values.

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.

Holdouts

A holdout keeps a share of units out of every experiment it covers, so their long-term effect can be measured. Holdouts arrive with the context data (ContextData::$holdouts) and cover the experiments that list them in holdoutIds; nothing needs configuring in the SDK.

  • A unit in a holdout's held-out arm (variant 0) gets control (variant 0) for each covered experiment, and getTreatment() sends no exposure for that experiment. In a 3-arm holdout, arm 1 holds out only experiments that are not full-on.
  • The first getTreatment() on a covered experiment sends one exposure for each of its holdouts (once per holdout and unit type), with the holdout's arm as the variant. A getVariableValue() read exposes only the winner experiment and its holdouts, plus the holdouts of suppressed candidates visited before it (or all visited suppressed candidates when nothing wins). It does not expose every covered candidate. peekTreatment() and peekVariableValue() send nothing.
  • An override (setOverride()) and a matching assignment rule win over a holdout; a custom assignment does not.
  • For a variable key shared by several experiments, a held-out experiment never wins the key (the unit is not assigned to it), but getVariableValue() still sends its holdouts' exposures when it visits that candidate. When no experiment wins the key, the first held-out experiment's control value is returned (if its control variant defines the key).

When creating a context from pre-fetched data, pass the holdouts too:

$contextData = new ContextData($payload->experiments, $payload->holdouts ?? []);
$context = $sdk->createContextWithData($contextConfig, $contextData);

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.

$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/<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');

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.

$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);

Tracking Goals

Goals are created in the A/B Smartly Web Console.

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

$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 publishes any queued events to the A/B Smartly collector, like Context->publish(), and closes the context. As with publish(), a context whose initial load failed drops its queued events instead of sending them (see Refreshing the Context), so a successful close() does not mean every event was delivered. Event-generating operations such as track() and getTreatment() then throw; attribute and unit setters remain usable as in 1.0.3.

$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

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:

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 Throwable 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 An exposure is queued (first getTreatment()/getVariableValue()) Exposure data enqueued; sent to the collector on publish
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.

// 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\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\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');
        }
    }
}

Using with Symfony

Symfony applications can integrate A/B Smartly using dependency injection and event subscribers for request lifecycle management.

// 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
<?php

namespace App\EventSubscriber;

use ABSmartly\SDK\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');
        }
    }
}

Advanced Request Configuration

Request Timeout Override

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\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:

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, 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 entries under it. Then record the new section's hash in RELEASED_SECTIONS in tests/Client/ReleaseVersionTest.php; the failing test prints the line to add.
  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: composer install && php .github/scripts/check-release-version.php vX.Y.Z && git tag vX.Y.Z && git push origin vX.Y.Z.
  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:

See CHANGELOG.md for release notes.

About

A/B Smartly php-sdk

Resources

Stars

2 stars

Watchers

2 watching

Forks

Releases

Packages

Used by

Contributors

Languages