Download the PHP package absmartly/php-sdk without Composer
On this page you can find all versions of the php package absmartly/php-sdk. It is possible to download/install these versions without Composer. Possible dependencies are resolved automatically.
Download absmartly/php-sdk
More information about absmartly/php-sdk
Files in absmartly/php-sdk
Package php-sdk
Short Description A/B Smartly PHP SDK for running experiments and feature flags with the A/B Smartly platform.
License MIT
Homepage https://github.com/absmartly/php-sdk
Informations about the package php-sdk
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.
Backwards Compatibility Note
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.
Migrating to 2.0 (breaking)
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.
Installation
A/B Smartly PHP SDK can be installed with composer:
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:
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:
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:
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 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.
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) |
Creating a New Context
Synchronously
Asynchronously (with ReactPHP)
When using the async HTTP client, context creation is non-blocking:
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.
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:
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.
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.
Basic Usage
Selecting a Treatment
Treatment Variables
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.
Peeking at Variables
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.
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.
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):
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.
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.
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:
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.
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.
Tracking Goals
Goals are created in the A/B Smartly Web Console.
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.
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 will also "seal" the context, throwing an error if any method that could generate an event is called.
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
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:
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.
Using with Symfony
Symfony applications can integrate A/B Smartly using dependency injection and event subscribers for request lifecycle management.
Advanced Request Configuration
Request Timeout Override
PHP supports per-request timeout configuration through HTTP client options:
Async Request with ReactPHP
For non-blocking operations with cancellation support:
Releasing
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.
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
- 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.
All versions of php-sdk with dependencies
lastguest/murmurhash Version ~2.1.1
ext-curl Version *
ext-json Version *