PHP V2.0.X
Introduction
SDK overview
Welcome to the Flagship PHP SDK documentation!
The following article will guide you through the steps to get Flagship up and running on your PHP scripts using our library with preconfigured methods to implement the Decision API or Bucketing CDN.
Feel free to contact us if you have any questions regarding this documentation.
SDK features
That SDK version helps you :
- Set a visitor ID
- Update user context
- Assign campaigns via the Decision API or the BucketingCDN
- Get modifications
- Manage visitor consent
- Use experience continuity
- Activate campaigns
- Send hits to our Universal Collect
Prerequisites
- PHP : version 5.4 or later
- php_curl extension must be enabled
- json extension must be enabled
- Composer : version 1.0.0 or later
- Your server/device must have an access to the internet.
Good to know
- Github repository: https://github.com/flagship-io/flagship-php-sdk
Getting Started
Installation
The Flagship PHP SDK can be installed with Composer. Follow the
installation instructions if the composer is not already installed.
Once composer is installed, in your project root run the following command to install this library:
composer require flagship-io/flagship-php-sdk
Initialization
To initialize and start the SDK, simply call the start
function of the \Flagship\Flagship
class, in the most appropriate location for your application.
require __DIR__ . '/vendor/autoload.php';
use Flagship\Flagship;
Flagship::start("your_env_id", "your_api_key");
Parameter | Type | Description |
---|---|---|
envId | String | Environment id provided by Flagship. |
apiKey | String | Api authentication key provided by Flagship. |
config | - \Flagship\Config\DecisionApiConfig - \Flagship\Config\BucketingConfig | (optional) Custom flagship configuration. |
Flagship config
This class aims to help you to configure the SDK via the following two configurations: DecisionApi and Bucketing. See Decision Mode section.
//Start sdk in Decision api mode.
use Flagship\Config\FlagshipConfig;
use Flagship\Enum\FlagshipStatus;
use Flagship\Enum\LogLevel;
$config = FlagshipConfig::decisionApi()
->setLogManager(new CustomLogManager())
->setLogLevel(LogLevel::ALL)
->setTimeout(2000)
->setStatusChangedCallback(function ($status) {
if ($status === FlagshipStatus::READY) {
echo "SDK is ready";
}
});
Flagship::start("your_env_id", "your_api_key", $config);
//Start sdk in Bucketing mode.
use Flagship\Config\FlagshipConfig;
use Flagship\Enum\FlagshipStatus;
use Flagship\Enum\LogLevel;
$config = FlagshipConfig::bucketing()
->setLogManager(new CustomLogManager())
->setLogLevel(Flagship\Enum\LogLevel::ALL)
->setTimeout(2000)
->setStatusChangedCallback(function ($status) {
if ($status === FlagshipStatus::READY) {
echo "SDK is ready";
}
})
->setBucketingDirectoryPath("customDirectory");
Flagship::start("your_env_id", "your_api_key", $config);
-
public function setLogManager(Psr\Log\LoggerInterface $logManager) : Flagship\Config\FlagshipConfig
Specify a custom implementation of LogManager in order to receive logs from the SDK.
Parameter | Type | Description |
---|---|---|
logManager | Psr\Log\LoggerInterface | Custom implementation of LogManager. |
-
public function setLogLevel(int $logLevel) : \Flagship\Config\FlagshipConfig
This method specify the mode which filter SDK logs.
Parameter | Type | Description |
---|---|---|
level | int | see \Flagship\Enum\LogLevel . The levels in ascending order are : - NONE = 0, - EMERGENCY = 1, - ALERT = 2, - CRITICAL = 3, - ERROR = 4, - WARNING = 5, - NOTICE = 6, - INFO = 7, - DEBUG = 8, - ALL = 9; |
-
public function setTimeout(int $timeout) : \Flagship\Config\FlagshipConfig
Specify timeout for api request.
Parameter | Type | Description |
---|---|---|
timeout | int | Milliseconds for connect and read timeouts. Default is 2000ms. |
-
public function setStatusChangedCallback(callable $statusChangedCallback) \Flagship\Config\FlagshipConfig
Define a callable function in order to get callback when the SDK status has changed. See SDK status section.
Parameter | Type | Description |
---|---|---|
statusChangedCallback | callable | Callback to trigger when SDK status has changed. |
Only available for Bucketing:
Bucketing Directory path
-
public function setBucketingDirectoryPath(string $bucketingDirectoryPath) \Flagship\Config\BucketingConfig
Define the directory path where the SDK will find the bucketing file from polling process
Parameter | Type | Description |
---|---|---|
bucketingDirectoryPath | string | directory path |
Default path is
/webroot/vendor/flagship-io/flagship
Decision Mode
DecisionApi
Mode
When the SDK is running in DecisionApi
mode, the campaign assignments and targeting validation take place server-side. In this mode, each call to the synchronizeModifications
method to refresh the modifications will create an HTTP request.
Bucketing
Mode
In Bucketing
mode, when synchronizeModifications
method is called. The SDK will check the bucketing file
in bucketing directory path . Then validates campaigns targeting the visitor and assigns a variation. Learn more
In order to feed bucketing file
, you must run bucketing polling process. See Bucketing polling section.
SDK Status
List of possible SDK status :
class Flagship\Enum\FlagshipStatus
Status | type | Description |
---|---|---|
FlagshipStatus::NOT_INITIALIZED | int | Flagship SDK has not been started or initialized successfully. |
FlagshipStatus::STARTING | int | Flagship SDK is starting. |
FlagshipStatus::READY_PANIC_ON | int | Flagship SDK is ready but is running in Panic mode: All visitors features are disabled except 'synchronization' which refresh this status. |
FlagshipStatus::READY | int | Flagship SDK is ready to use. |
Bucketing polling
There are two ways to start bucketing polling process :
- Using vendor binary command
- Using flagship-sync-agent
Both ways download all the campaigns configurations at once in a single bucketing file and stores it in bucketing directory path define through the argument bucketingPath.
The bucketing file is updated each time interval define through pollingInterval argument.
Vendor binary command
The SDK comes with a vendor binary command vendor/bin/flagship
.
vendor/bin/flagship --envId=envId --pollingInterval=2000 --bucketingPath=customDirectory
This command starts bucketing polling process using values passed through arguments
Flagship-sync-agent
flagship-sync-agent is a binary that performs the bucketing polling process.
You can download it here
./flagship-sync-agent --envId=envId --pollingInterval=2000 --bucketingPath=customDirectory
arguments:
argument | type | description |
---|---|---|
envId | string | Environment id provided by Flagship. |
pollingInterval | int | Define time interval between two bucketing updates. Default is 2000ms. |
bucketingPath | string | (optional) Directory path where bucketing file will be saved. Default path is : - /webroot/vendor/flagship-io/flagship for vendor binary command - ./flagship for flagship-sync-agent |
config | string | flagship configuration file path. See flagship configuration file section |
Flagship configuration file
Flagship configuration is a JSON file containing a set of options that bucketing polling process can use instead of passing arguments one by one.
// ~/webroot/flagship.json
{
"envId" : "env_id",
"pollingInterval": 2000,
"bucketingPath": "flagship"
}
Code example using bucketing polling process with a configuration file:
~/webroot$ vendor/bin/flagship --config=flagship.json
//or
~/webroot$ ./flagship-sync-agent --config=flagship.json
Create a new visitor
The \Flagship\Visitor\Visitor
instance is an helper object that lets you manage the context and campaigns for a user identified by a unique ID.
The user context is a property dataset which defines the current user of your app. This dataset is sent and used as targeting criteria for campaign assignment.
For example, if you want to enable or disable a specific feature based on a VIP
status, you would pass this attribute as a key-value pair in the user context so that the Decision API can enable or disable the corresponding feature flag for the user.
use Flagship\Flagship;
$visitor = Flagship::newVisitor("your_visitor_id")
->hasConsented(true)
->withContext(["age" => 31, "isVip" => true])
->isAuthenticated(true)
->build();
-
public static function newVisitor(string $visitorId) : \Flagship\Visitor\VisitorBuilder
Initialize the builder and Return a
\Flagship\Visitor\VisitorBuilder
or null if the SDK hasn't started successfully.Parameter Type Description visitorId string Unique visitor identifier.
VisitorBuilder
\Flagship\Visitor\VisitorBuilder
is a fluent interface builder api managing Visitor creation.
-
public function isAuthenticated(bool $isAuthenticated) : \Flagship\Visitor\VisitorBuilder
Specify if the Visitor is authenticated or anonymous.
Parameter Type Description isAuthenticated bool true for an authenticated visitor, false for an anonymous visitor. -
public function hasConsented(bool $hasConsented) : \Flagship\Visitor\VisitorBuilder
Specify if the Visitor has consented for personal data usage. When false some features will be deactivated, cache will be deactivated and cleared.
Parameter Type Description hasConsented bool Set to true when the visitor has consented, false otherwise. -
public function withContext(array $context) : \Flagship\Visitor\VisitorBuilder
Specify Visitor initial context key / values used for targeting.
Parameter Type Description context array (associative array) visitor initial context.
e.g: ["age"=>42, "IsVip"=>true, "country"=>"UK"].
- User context keys must have a type of
string
- User context values must have a type of
string
,bool
,numeric
- User context keys and values are case sensitive
-
public function build() : \Flagship\Visitor\Visitor
Complete the Visitor Creation process and return an instance of
\Flagship\Visitor\Visitor
Updating the visitor context
The user context is a property dataset that defines the current user of your app. This dataset is sent and used as targeting criteria for campaign assignment.
The following method from the \Flagship\Visitor\Visitor
instance allows you to set new context values matching the given keys.
use Flagship\Flagship;
Flagship::start("your_env_id", "your_api_key");
$visitor = Flagship::newVisitor("your_visitor_id")
->withContext(["age" => 31, "isVip" => true])
->build();
$visitor->updateContext("lastPurchaseDate", 1615384464);
public function updateContext(string $key, bool|numeric|string $value) : void
Update the visitor context values, matching the given keys, used for targeting.
Parameter | Type | Description |
---|---|---|
key | String | Context key. |
value | bool or numeric or string | Context value. |
public function updateContextCollection(array $Context) : void
Update the visitor context values, matching the given keys, used for targeting.
Parameter | Type | Description |
---|---|---|
context | array (associative array) | collection of keys, values. |
public function getContext(): array
Get all the visitor's current context as a collection of keys, values
public function clearContext() : void
Clear the actual visitor context
- User context keys must have a type of
string
- User context values must have a type of
string
,bool
,numeric
- User context keys and values are case sensitive
update context with predefined keys of context
use Flagship\Flagship;
use Flagship\Enum\FlagshipContext;
Flagship::start("your_env_id", "your_api_key");
$visitor = Flagship::newVisitor("your_visitor_id")
->withContext(["age" => 31, "isVip" => true])
->build();
$visitor->updateContext(FlagshipContext::OS_NAME, "linux");
$visitor->updateContext(FlagshipContext::IP, "127.0.0.1");
Learn more about predefined keys of context
Managing visitor campaigns
Synchronizing campaigns
The synchronizeModifications()
method of the \Flagship\Visitor\Visitor
instance, according to Decision Mode, will either automatically call the Flagship Decision API to run campaign assignments according to the current user context and retrieve applicable modifications; or check the bucketing file
, validate campaigns targeting the visitor, assign a variation and retrieve applicable modifications.
These modifications are then stored in the SDK and updated synchronously when synchronizeModifications()
is called.
use Flagship\Flagship;
Flagship::start("your_env_id", "your_api_key");
$visitor = Flagship::newVisitor("your_visitor_id")->build()
$visitor->updateContext("postcode", "31200")
visitor->synchronizeModifications();
public function synchronizeModifications() : void
In DecisionApi Mode this function calls the Flagship Decision API to run campaign assignments according to the current user context and retrieve applicable modifications.
In bucketing Mode, it checks the bucketing file, validates campaigns targeting the visitor, assigns a variation, and retrieves applicable modifications
Getting modifications
Once the campaign has been assigned and synchronized, all the modifications are stored in the SDK. You can retrieve these modifications using the following functions from the \Flagship\Visitor
instance:
use Flagship\Flagship;
Flagship::start("your_env_id", "your_api_key");
$visitor = Flagship::newVisitor("your_visitor_id")->build()
$visitor->updateContext("isVip", true)
$visitor->synchronizeModifications();
$displayVipFeature = $visitor->getModification("displayVipFeature", false);
public function getModification(string $key, bool|numeric|string|array $defaultValue, bool $activate = false) : bool|numeric|string|array
Retrieve a modification value by its key. If no modification matches the given key or if the stored value type and default value type do not match, the default value will be returned.
Parameter | Type | Description |
---|---|---|
key | string | key associated to the modification. |
defaultValue | bool or numeric or string or array | default value to return. |
activate | bool | (optional) set this parameter to true to automatically report on our server that the current visitor has seen this modification. It is possible to call activateModification() later. |
- Default value must be one of the following type :
string
,bool
,numeric
,array
.
Getting campaign information
You may need to send campaign IDs to a third-party for reporting and/or analytics purposes. It is possible to retrieve campaigns IDs for a specific modification key.
use Flagship\Flagship;
Flagship::start("your_env_id", "your_api_key");
$visitor = Flagship::newVisitor("your_visitor_id")->build();
$visitor->updateContext("isVip", true);
$visitor->synchronizeModifications();
$info = $visitor->getModificationInfo("displayVipFeature");
public function getModificationInfo(string $key) : array|null
Parameter | Type | Description |
---|---|---|
key | String | Key associated with the modification. |
It returns an array containing campaignId
, variationGroupId
, variationId
and isReference
keys & values or null if the modification is not found (the user is not affected to the campaign linked to the modification).
Activating modifications
Once a modification is displayed on the screen for a user, you must send an activate event to tell Flagship that the user has seen it.
There are two options for activating a modification:
- Pass an
activate=true
parameter to the getModification() function - Use the following activateModification() method from the visitor instance.
use Flagship\Flagship;
Flagship::start("your_env_id", "your_api_key");
$visitor = Flagship::newVisitor("your_visitor_id")->build();
$visitor->updateContext("isVip", true);
$visitor->synchronizeModifications();
//send an activation event.
$displayVipFeature = $visitor->getModification("displayVipFeature", false, true);
//or
$displayVipFeature = $visitor.getModification("displayVipFeature", false);
$visitor.activateModification("displayVipFeature");
public function activateModification(string $key) : void
Report this user has seen this modification.
Parameter | Type | Description |
---|---|---|
key | String | key associated to the modification to report. |
Managing visitor consent
The \Flagship\Visitor\Visitor
class provides a method to let you manage visitor consent for data privacy usage. When False, campaign activation and hits will be disabled.
use Flagship\Flagship;
Flagship::start("your_env_id", "your_api_key");
$visitor = Flagship::newVisitor("your_visitor_id")->build();
$visitor->setConsent(false);
public function setConsent(bool $hasConsented) : \Flagship\Visitor\Visitor
Parameter | Type | Description |
---|---|---|
hasConsented | bool | Set visitor consent for private data usage. When false some features will be deactivated. |
public function hasConsented() : bool
Return true
if the visitor has consented for private data usage, otherwise, return false
.
Experience Continuity
In some situations, you may want experience consistency between an anonymous visitor and an authenticated visitor. Flagship provides the following two methods in order to help you to specify when a visitor is authenticated or not.
Authenticate
public function authenticate(string $visitorId) : void
Parameter | Type | Description |
---|---|---|
visitorId | string | id of the new authenticated visitor. |
Unauthenticate
public function unauthenticate() : void
Code example
use Flagship\Flagship;
Flagship::start("your_env_id", "your_api_key");
$visitor = Flagship::newVisitor("anonymous")->build(); // anonymous visitor lands on your app.
// Once the visitor log in and is authenticated on your app.
$visitor->authenticate("visitor_id");
// Once the visitor log out and is unauthenticed on your app.
$visitor->unauthenticate();
Hit Tracking
This section helps you track your users in your application and learn how to build hits in order to feed your reports. For more information about our measurement protocol, read our Universal Collect documentation.
There are four different types of Hits available:
- Page
- Transaction
- Item
- Event
They must all be built and sent with the following function from the Flagship\Visitor
instance:
use Flagship\Flagship;
use Flagship\Hit\Page;
$visitor = Flagship::newVisitor("your_visitor_id")->build();
$visitor->sendHit(new Page("https://www.my_domain_com/my_page"));
public function sendHit(HitAbstract $hit) : void
Report this user has seen this modification.
Parameter | Type | Description |
---|---|---|
hit | HitAbstract | Hit to send. |
Hit common optional parameters
use Flagship\Flagship;
use Flagship\Hit\Page;
$visitor = Flagship::newVisitor("your_visitor_id")->build();
$visitor->sendHit(new Page("https://www.my_domain_com/my_page")
->setUserIp("127.0.0.1")
->setScreenResolution("800X600")
->setLocale("fr")
->setSessionNumber("12345")
);
Builder Parameter | Type | Description |
---|---|---|
setUserIp | String | User IP |
setScreenResolution | string | Screen resolution. |
setLocale | String | User language |
setSessionNumber | string | Session number |
Page
This hit should be sent each time a visitor arrives on a new page.
use Flagship\Hit\Page;
$page = new Page("https://www.my_domain_com/my_page")
$visitor->sendHit($page);
public Page(string $pageUrl)
Builder Parameter | Type | Description |
---|---|---|
pageUrl | String | Valid url. |
Transaction
This hit should be sent when a user completes a transaction.
use Flagship\Hit\Transaction;
$transaction = (new Transaction("#12345", "affiliation"))
->setCouponCode("code")
->setCurrency("EUR")
->setItemCount(1)
->setPaymentMethod("creditCard")
->setShippingCosts(9.99)
->setTaxes(19.99)
->setTotalRevenue(199.99)
->setShippingMethod("1day");
$visitor->sendHit($transaction);
public Transaction(string $transactionId, string $affiliation)
Builder Parameter | Type | Description |
---|---|---|
transactionId | String | Unique identifier for your transaction. |
affiliation | String | The name of the KPI that you will have inside your reporting. Learn more |
setTotalRevenue | float | Specifies the total revenue associated with the transaction. This value should include any shipping and/or tax amounts. |
setShippingCosts | float | The total shipping cost of your transaction. |
setShippingMethod | String | The shipping method for your transaction. |
setTaxes | float | Specifies the total amount of taxes in your transaction. |
setCurrency | String | Specifies the currency of your transaction. NOTE: This value should be a valid ISO 4217 currency code. |
setPaymentMethod | String | Specifies the payment method used for your transaction. |
setItemCount | int | Specifies the number of items in your transaction. |
setCouponCode | String | Specifies the coupon code used by the customer in your transaction. |
Item
This hit is used to link an item with a transaction. It must be sent after the corresponding transaction hit.
use Flagship\Hit\Item;
$item = (new Item("#12345", "product", "sku123"))
->setItemCategory("test")
->setItemPrice(199.99)
->setItemQuantity(1);
$visitor->sendHit($item);
public Item(string $transactionId, string $productName, string $productSku)
Builder Parameter | Type | Description |
---|---|---|
transactionId | String | Unique identifier for your transaction. |
productName | String | Name of your item. |
productSku | String | Specifies the SKU or item code. |
setItemCategory | String | Specifies the category that the item belongs to. |
setItemPrice | float | Specifies the price for a single item/unit. |
setItemQuantity | int | Specifies the number of items purchased. |
Event
This hit can be used for any event (e.g. Add To Cart click, newsletter subscription).
use Flagship\Hit\Event;
$event = (new Event(EventCategory::USER_ENGAGEMENT, "action"))
->setLabel("label")
->setValue(100);
$visitor->sendHit($event);
public Event(EventCategory category, String action)
Builder Parameter | Type | Description |
---|---|---|
category | EventCategory | Specifies the category of your event. NOTE: This value must be either Flagship\Enum\EventCategory::ACTION_TRACKING or Flagship\EnumEventCategory::USER_ENGAGEMENT . |
action | String | Event name that will also serve as the KPI that you will have inside your reporting. Learn more |
setLabel | String | (optional) Additional description of your event. |
setValue | Number | (optional) Specifies the monetary value associated with an event (e.g. you earn 10 to 100 euros depending on the quality of lead generated). NOTE: this value must be non-negative. |
Appendix
Predefined user context keys
The Flagship SDK contains predefined user context keys.
The keys marked as Yes in the Auto-set by SDK column will be automatically set, while the ones marked as No need to be set by customer.
You can overwrite these keys at any time. The key-value pairs will be sent to the server in the user context and can be edited in the Persona section of the Flagship platform.
To overwrite the keys, use the
updateContext
method
SDK constant Name | Description | Context variable name | Type | Auto-set by SDK | Example |
---|---|---|---|---|---|
FlagshipContext::DEVICE_LOCALE | Language of the device | sdk_deviceLanguage | String | No | fra |
FlagshipContext::DEVICE_TYPE | Type of the device | sdk_deviceType | DeviceType | No | Mobile |
FlagshipContext::DEVICE_MODEL | Model of the device | sdk_deviceModel | String | No | samsung E1200 |
FlagshipContext::LOCATION_CITY | City geolocation | sdk_city | String | No | toulouse |
FlagshipContext::LOCATION_REGION | Region geolocation | sdk_region | String | No | occitanie |
FlagshipContext::LOCATION_COUNTRY | Country geolocation | sdk_country | String | No | France |
FlagshipContext::LOCATION_LAT | Current Latitude | sdk_lat | Double | No | 43.623647 |
FlagshipContext::LOCATION_LONG | Current Longitude | sdk_long | Double | No | 1.445397 |
FlagshipContext::IP | IP of the device | sdk_ip | String | No | 127.0.0.1 |
FlagshipContext::OS_NAME | Name of the OS | sdk_osName | String | YES | ubuntu / centos |
FlagshipContext::OS_VERSION_NAME | Version name of the OS | sdk_osVersionName | String | No | 9.0.0 |
FlagshipContext::OS_VERSION_CODE | Version code of the OS | sdk_osVersionCode | Number | No | 24 |
FlagshipContext::CARRIER_NAME | Name of the carrier or mobile virtual network operator | sdk_carrierName | String | No | free |
FlagshipContext::INTERNET_CONNECTION | What is the internet connection | sdk_internetConnection | String | No | 5g |
FlagshipContext::APP_VERSION_NAME | Version name of the app | sdk_versionName | String | No | 1.1.2-beta |
FlagshipContext::APP_VERSION_CODE | Version code of the app | sdk_versionCode | Number | No | 40 |
FlagshipContext::INTERFACE_NAME | Name of the interface | sdk_interfaceName | String | No | ProductPage |
FlagshipContext::FLAGSHIP_CLIENT | Flagship SDK client (Reserved) | fs_client | String | Yes | PHP |
FlagshipContext::FLAGSHIP_VERSION | Version of the Flagship SDK (Reserved) | fs_version | String | Yes | 2.0.0 |
Updated 5 months ago