PHPackages                             absmartly/php-sdk - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [API Development](/categories/api)
4. /
5. absmartly/php-sdk

ActiveLibrary[API Development](/categories/api)

absmartly/php-sdk
=================

v1.0.3(3y ago)226.2k—7.1%1[4 PRs](https://github.com/absmartly/php-sdk/pulls)MITPHPCI failing

Since Nov 10Pushed 1w ago3 watchersCompare

[ Source](https://github.com/absmartly/php-sdk)[ Packagist](https://packagist.org/packages/absmartly/php-sdk)[ RSS](/packages/absmartly-php-sdk/feed)WikiDiscussions main Synced yesterday

READMEChangelogDependencies (3)Versions (9)Used By (0)

A/B Smartly SDK
===============

[](#ab-smartly-sdk)

A/B Smartly PHP SDK

Compatibility
-------------

[](#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.

Getting Started
---------------

[](#getting-started)

### Install the SDK

[](#install-the-sdk)

A/B Smartly PHP SDK can be installed with [`composer`](https://getcomposer.org):

```
composer require absmartly/php-sdk
```

Import and Initialize the SDK
-----------------------------

[](#import-and-initialize-the-sdk)

Once the SDK is installed, it can be initialized in your project.

You can create an SDK instance using the API key, application name, environment, and the endpoint URL obtained from A/B Smartly.

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

```
use \ABSmartly\SDK\SDK;

$sdk = SDK::createWithDefaults(
  $endpoint, $apiKey, $environment, $application,
);
```

The above is a short-cut that creates an SDK instance quickly using default values. If you would like granular choice of individual components (such as a custom event logger), it can be done as following:

```
use ABSmartly\SDK\Client\ClientConfig;
use ABSmartly\SDK\Client\Client;
use ABSmartly\SDK\Config;
use ABSmartly\SDK\SDK;
use ABSmartly\SDK\Context\ContextConfig;
use ABSmartly\SDK\Context\ContextEventLoggerCallback;

$clientConfig = new ClientConfig('', '', '', '');
$client = new Client($clientConfig);
$config = new Config($client);

$sdk = new SDK($config);

$contextConfig = new ContextConfig();
$contextConfig->setEventLogger(new ContextEventLoggerCallback(
    function (string $event, ?object $data) {
        // Custom callback
    }
));

$context = $sdk->createContext($contextConfig);
```

**SDK Options**

ConfigTypeRequired?DefaultDescription`endpoint`string✅*undefined*The URL to your API endpoint. Most commonly "your-company.absmartly.io"`apiKey``string`✅*undefined*Your API key which can be found on the Web Console.`environment``"production"` or `"development"`✅*undefined*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`✅*undefined*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`❌5The number of retries before the SDK stops trying to connect.`eventLogger``\ABSmartly\SDK\Context\ContextEventLogger`❌`null`, See Using a Custom Event Logger belowA callback function which runs after SDK events.### Using a Custom Event Logger

[](#using-a-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`.

```
use ABSmartly\SDK\Client\ClientConfig;
use ABSmartly\SDK\Context\ContextEventLoggerCallback;

$contextConfig = new ContextConfig();
$contextConfig->setEventLogger(new ContextEventLoggerCallback(
    function (string $event, ?object $data) {
        // Custom callback
    }
));
```

Alternately, it is possible to implement `\ABSmartly\SDK\Context\ContextEventLogger` interface with `handleEvent()` method that receives the `Context` object itself, along with a `ContextEventLoggerEvent` object as shown below:

```
use \ABSmartly\SDK\Context\ContextEventLoggerCallback;

class CustomLogger implements ContextEventLogger {
    public function handleEvent(Context $context, ContextEventLoggerEvent $event): void {
        // Process the log event
        // e.g
        // myLogFunction($event->getEvent(), $event->getData());
    }
}

$contextConfig = new ContextConfig();
$contextConfig->setEventLogger(CustomLogger());
```

The data parameter depends on the type of event. Currently, the SDK logs the following events:

eventNamewhendata`"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`GoalAchivement` goal data enqueued for publishing`"Close"``Context->lose()` method succeeds the first time`null`Create a New Context Request
----------------------------

[](#create-a-new-context-request)

**Synchronously**

```
$contextConfig = new ContextConfig();
$contextConfig->setUnit('session_id', 'session_id5ebf06d8cb5d8137290c4abb64155584fbdb64d8'); // a unique id identifying the user

$context = $sdk->createContext($contextConfig);
```

**With Prefetched Data**

```
$contextConfig = new ContextConfig();
$contextConfig->setUnit('session_id', 'session_id5ebf06d8cb5d8137290c4abb64155584fbdb64d8'); // a unique id identifying the user

$context = $sdk->createContext($contextConfig);

$anotherContextConfig = new ContextConfig();
$anotherContextConfig->setUnit('session_id', 'session_id5ebf06d8cb5d8137290c4abb64155584fbdb64d8'); // a unique id identifying the user

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

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

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

```
$context->setUnit('user_id', 143432);
```

Basic Usage
-----------

[](#basic-usage)

### Selecting A Treatment

[](#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

[](#treatment-variables)

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

### Peek at Treatment Variants

[](#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

[](#peeking-at-variables)

```
$buttonColor = $context->peekVariableValue('button.color', 'red');
```

### Overriding Treatment Variants

[](#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
--------

[](#advanced)

### Context Attributes

[](#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('session_id', \session_id());
$context->setAttributes(
    [
        'customer_age' => 'new_customer'
    ]
);
```

### Custom Assignments

[](#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);
```

### Publish

[](#publish)

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();
```

### Finalize

[](#finalize)

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();
```

### Tracking Goals

[](#tracking-goals)

```
$context->track(
    'payment',
    (object) ['item_count' => 1, 'total_amount' => 1999.99]
);
```

###  Health Score

42

—

FairBetter than 88% of packages

Maintenance64

Regular maintenance activity

Popularity29

Limited adoption so far

Community13

Small or concentrated contributor base

Maturity52

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 93.2% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~29 days

Total

4

Last Release

1241d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/e9e15cf011692db4b076d75cf9497585df36dfb673524480a8756b27b56d6ca3?d=identicon)[absmartly](/maintainers/absmartly)

---

Top Contributors

[![Ayesh](https://avatars.githubusercontent.com/u/811553?v=4)](https://github.com/Ayesh "Ayesh (41 commits)")[![marcio-absmartly](https://avatars.githubusercontent.com/u/77632139?v=4)](https://github.com/marcio-absmartly "marcio-absmartly (2 commits)")[![marcioapm](https://avatars.githubusercontent.com/u/212230?v=4)](https://github.com/marcioapm "marcioapm (1 commits)")

---

Tags

absmartly

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/absmartly-php-sdk/health.svg)

```
[![Health](https://phpackages.com/badges/absmartly-php-sdk/health.svg)](https://phpackages.com/packages/absmartly-php-sdk)
```

###  Alternatives

[pocketmine/pocketmine-mp

A server software for Minecraft: Bedrock Edition written in PHP

3.5k78.3k91](/packages/pocketmine-pocketmine-mp)[phptg/bot-api

PHP library for working with Telegram API

12716.4k7](/packages/phptg-bot-api)[biplane/yandex-direct

PHP library for Yandex.Direct API

55187.0k2](/packages/biplane-yandex-direct)[furqansiddiqui/erc20-php

Interact with any ERC20 standard/backward-compatible Ethereum token

16467.4k4](/packages/furqansiddiqui-erc20-php)[benmorel/ebay-sdk-php

An eBay SDK for PHP. Fork of dts/ebay-sdk-php with support for PHP 8.

35556.6k](/packages/benmorel-ebay-sdk-php)[billbee/billbee-api

The official Billbee API SDK for PHP

24136.0k](/packages/billbee-billbee-api)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
