PHP V3.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 :

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

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");
ParameterTypeDescription
envIdStringEnvironment id provided by Flagship.
apiKeyStringApi 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("http://127.0.0.1:8080/bucketing")
    ->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);
  • public static function FlagshipConfig::decisionApi() : Flagship\Config\DecisionApiConfig

Initialize the SDK to start with Decision-Api mode

  • public static function FlagshipConfig::bucketing(string $bucketingUrl) : Flagship\Config\BucketingConfig

Initialize the SDK to start with Bucketing-mode

Parameter

Type

Description

bucketingUrl

string

flagship-sync-agent endpoint URL

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

  • public function setVisitorCacheImplementation(IVisitorCacheImplementation $visitorCacheImplementation) : \Flagship\Config\FlagshipConfig

Define an object that implement the interface IVisitorCacheImplementation, to handle the visitor cache.
see cache-manager

Parameter

Type

Description

visitorCacheImplementation

Flagship\Cache\IVisitorCacheImplementation

implementation of IVisitorCacheImplementation interface

Only available for Bucketing:

Bucketing file url

  • public function setBucketingUrl(string $bucketingUrl): \Flagship\Config\BucketingConfig

    Define the flagship-sync-agent endpoint URL where the SDK will fetch the bucketing file from polling process

Parameter

Type

Description

bucketingUrl

string

flagship-sync-agent endpoint URL

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 fetchFlags method to refresh the modifications will create an HTTP request.

Bucketing Mode

In Bucketing mode, when fetchFlags method is called. The SDK will check the bucketing file fetched through flagship-sync-agent endpoint URL . 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

StatustypeDescription
FlagshipStatus::NOT_INITIALIZEDintFlagship SDK has not been started or initialized successfully.
FlagshipStatus::STARTINGintFlagship SDK is starting.
FlagshipStatus::READY_PANIC_ONintFlagship SDK is ready but is running in Panic mode: All visitors features are disabled except 'synchronization' which refresh this status.
FlagshipStatus::READYintFlagship SDK is ready to use.

Bucketing polling

To start bucketing polling, you need to run in your infrastructure flagship-sync-agent. This binary is a local endpoint (API) that provides the bucketing file which is downloaded from flagship CDN by performing the bucketing polling process.

flagship-sync-agent downloads all the campaigns configurations at once in a single bucketing file and stored it in cache. It will only be downloaded again when campaign configurations are modified in the Flagship interface.

The gain of going through flagship-sync-agent is in terms of response time. once it has downloaded the bucketing file, it delivers it within a very short time to the script that requests it.

You can download it here

$ ./app --envId=YOUR_ENV_ID --pollingInterval=2000 --port=3000 --address=0.0.0.0

arguments:

argumenttypedescription
envIdstringEnvironment id provided by Flagship.
pollingIntervalintDefine time interval between two bucketing updates. Default is 2000ms.
PortintEndpoint listen port. Default is 8080
addressstringAddress where the endpoint is served. Default is 0.0.0.0

Docker

docker pull flagshipio/sync-agent

env FS_ENV_ID="YOUR_ENV_ID" docker run -p 3000:8080 -e FS_ENV_ID flagshipio/sync-agent

Environment variables:

argumenttypedescription
FS_ENV_IDstringEnvironment id provided by Flagship.
FS_POLLING_INTERVALintDefine time interval between two bucketing updates. Default is 2000ms.
FS_PORTintEndpoint listen port. Default is 8080
FS_ADDRESSstringAddress where the endpoint is served. Default is 0.0.0.0

API docs

routeDescription
/bucketingGet the Json bucketing file
/health_checkReturn http code 200 to check if the sync agent is up

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.

    ParameterTypeDescription
    visitorIdstringUnique 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.

    ParameterTypeDescription
    isAuthenticatedbooltrue 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.

    ParameterTypeDescription
    hasConsentedboolSet 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.

    ParameterTypeDescription
    withContextarray (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.

ParameterTypeDescription
keyStringContext key.
valuebool or numeric or stringContext value.

public function updateContextCollection(array $Context) : void

Update the visitor context values, matching the given keys, used for targeting.

ParameterTypeDescription
contextarray (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")
              ->context(["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

Fetching Flags

The fetchFlags() 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 fetchFlags() 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->fetchFlags();

public function fetchFlags() : 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 flags

Once the campaign has been assigned and fetched, all the flags are stored in the SDK. You can retrieve these flags 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->fetchFlags();

$flag = $visitor->getFlag("displayVipFeature", false);

getFlag function

Return a Flag object by its key. If no flag match the given key an empty flag will be returned. Call exists() to check if the flag has been found.

  • public function getFlag(string $key, bool|numeric|string|array $defaultValue) : \Flagship\Flag\FlagInterface

Argument

Type

Description

key

string

Key associated to the flag

defaultValue

bool|numeric|string|array

Flag default value

🚧

  • Default value must be one of the following type : string, bool, numeric, array.

Getting flags current values

getValue function

To retrieve flag current value, simply call getValue() method of the Flag object.


use Flagship\Flagship;

Flagship::start("your_env_id", "your_api_key");
$visitor = Flagship::newVisitor("your_visitor_id")->build();
$visitor->updateContext("isVip", true);
$visitor->fetchFlags();

$flagValue = $visitor->getFlag("displayVipFeature", false)->getValue();
  • public function getValue(bool $userExposed) : bool|numeric|string|array function

Returns the value from the assigned campaign variation or the Flag default value if the Flag does not exist, or if types are different.

Parameter

Type

Default Value

Description

userExposed

Boolean

true

Tells Flagship the user have been exposed and have seen this flag. This will increment the visits for the current variation on your campaign reporting.
If needed it is possible to set this param to false and call userExposed() afterward when the user sees it.


Getting flags campaigns metadata

getMetadata function

You may need to send campaign IDs or variation IDs to a third party for reporting and/or analytics purposes. It is possible to retrieve campaigns metadata for a specific Flag.

use Flagship\Flagship;

Flagship::start("your_env_id", "your_api_key");
$visitor = Flagship::newVisitor("your_visitor_id")->build();
$visitor->updateContext("isVip", true);
$visitor->fetchFlags();

$campaignMetada = $visitor->getFlag("displayVipFeature", false)->getMetadata();

  • public function getMetadata() : FlagMetadata

Return the campaign information metadata or an empty object if the Flag doesn't exist or if the default value type does not correspond to the Flag type in Flagship.

The FlagMetadata class has the following shape:

gettersTypeDescription
getCampaignIdstringID of the campaign
getVariationGroupIdstring
getVariationIdstringThe variation ID assigned to the user
getIsReferencebooleanSpecify if its the reference variation
getCampaignTypestringcampaign type
getSlugstringcampaign slug

Report a Flag exposition

userExposed function

By default when the method getValue() is called, The SDK considers that the user have seen the effets of your Flag, unless you pass false to getValue(). In this case you will have to call userExposed().

There are two ways for exposing a user to a flag:

  1. Pass an userExposed=true parameter to the getValue() method.
  2. Use the following userExposed() method from the Flag instance.
use Flagship\Flagship;

Flagship::start("your_env_id", "your_api_key");
$visitor = Flagship::newVisitor("your_visitor_id")->build();
$visitor->updateContext("isVip", true);
$visitor->fetchFlags();

$campaignMetada = $visitor->getFlag("displayVipFeature", false)->userExposed();
  • public function userExposed() : void

Tells Flagship the user have been exposed and have seen this flag. This will increment the visits for the current variation on your campaign reporting. No user exposition will be sent if the Flag doesn't exist or if the default value type do not correspond to the Flag type in Flagship.


Check if a Flag exists

exists function

This method will return true if a Flag exists in Flagship

  • public function exists() : bool

use Flagship\Flagship;

Flagship::start("your_env_id", "your_api_key");
$visitor = Flagship::newVisitor("your_visitor_id")->build();
$visitor->updateContext("isVip", true);
$visitor->fetchFlags();

$exists = $visitor->getFlag("displayVipFeature", false)->exist();


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

ParameterTypeDescription
hasConsentedboolSet 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

ParameterTypeDescription
visitorIdstringid 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.

ParameterTypeDescription
hitHitAbstractHit 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 ParameterTypeDescription
setUserIpStringUser IP
setScreenResolutionstringScreen resolution.
setLocaleStringUser language
setSessionNumberstringSession 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 ParameterTypeDescription
pageUrlStringValid 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 ParameterTypeDescription
transactionIdStringUnique identifier for your transaction.
affiliationStringThe name of the KPI that you will have inside your reporting. Learn more
setTotalRevenuefloatSpecifies the total revenue associated with the transaction. This value should include any shipping and/or tax amounts.
setShippingCostsfloatThe total shipping cost of your transaction.
setShippingMethodStringThe shipping method for your transaction.
setTaxesfloatSpecifies the total amount of taxes in your transaction.
setCurrencyStringSpecifies the currency of your transaction. NOTE: This value should be a valid ISO 4217 currency code.
setPaymentMethodStringSpecifies the payment method used for your transaction.
setItemCountintSpecifies the number of items in your transaction.
setCouponCodeStringSpecifies 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 ParameterTypeDescription
transactionIdStringUnique identifier for your transaction.
productNameStringName of your item.
productSkuStringSpecifies the SKU or item code.
setItemCategoryStringSpecifies the category that the item belongs to.
setItemPricefloatSpecifies the price for a single item/unit.
setItemQuantityintSpecifies 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 ParameterTypeDescription
categoryEventCategorySpecifies the category of your event. NOTE: This value must be either Flagship\Enum\EventCategory::ACTION_TRACKING or Flagship\EnumEventCategory::USER_ENGAGEMENT.
actionStringEvent name that will also serve as the KPI that you will have inside your reporting. Learn more
setLabelString(optional) Additional description of your event.
setValueNumber(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.

Managing visitor cache

The purpose of the cache management is to answer the following needs:

  • Re-allocation in bucketing mode :

In bucketing mode and with the cache enabled, the SDK will always keep visitor in the variation he was allocated first, in case the customer manually changed the traffic allocation or the dynamic allocation feature was enabled, to avoid user experience issues. Indeed in bucketing mode the assignation is made on local devices so changing traffic allocation in the platform could authorize the visitors to see different variations.

  • Handle offline mode :

With the cache enabled, the SDK will try to retrieve the latest visitor data (campaign assignations) from the cache.

To use the cache manager the intefaces IVisitorCacheImplementation must be implemented through visitorCacheImplementation property accessor of configuration.

Visitor Cache

The visitor cache is used to store the visitor data in a database through the Flagship\Cache\IVisitorCacheImplementation interface.

interface IVisitorCacheImplementation
{
    public  function cacheVisitor($visitorId, array $data) : void;

    public function lookupVisitor($visitorId) : array;

    public function flushVisitor($visitorId) : void;
}

cacheVisitor function

This method is called when the SDK needs to cache visitor information in your database.

  • public function cacheVisitor($visitorId, array $data) : void

It has 2 arguments :

ArgumentTypeDescription
visitorIdstringvisitor ID
dataarrayvisitor data. The array has the follows shape see.

lookupVisitor function

This method is called when the SDK needs to get the visitor information corresponding to visitor ID from your database.

It has to return an array which follows this shape see.

  • public function lookupVisitor($visitorId) : array

It has one argument :

ArgumentTypeDescription
visitorIdstringvisitor ID

flushVisitor function

This method is called when the SDK needs to erase the visitor information corresponding to visitor ID in your database.

It will be called every time setConsent get false.

  • public function flushVisitor($visitorId) : void

It has one argument :

ArgumentTypeDescription
visitorIdstringvisitor ID

📘

  • flushVisitor method will be called every time setConsent get false.
Visitor Cache format
[
  'Version' => 1,
  'Data' => [
    'VisitorId' => 'visitor_1',
    'AnonymousId' => NULL,
    'Consent' => true,
    'Context' => [
      'qa_getflag' => true,
      'fs_client' => '.NET',
      'fs_version' => 'V3',
    ],
    'AssignmentsHistory' => [
      'xxxxxxxxxxxxxxxxxxxx' => 'xxxxxxxxxxxxxxxxxxxx',
      'yyyyyyyyyyyyyyyyyyyy' => 'yyyyyyyyyyyyyyyyyyyy',
    ],
    'Campaigns' => [
      0 => [
        'CampaignId' => 'xxxxxxxxxxxxxxxxxxxx',
        'VariationGroupId' => 'xxxxxxxxxxxxxxxxxxxx',
        'VariationId' => 'xxxxxxxxxxxxxxxxxxxx',
        'IsReference' => false,
        'Type' => 2,
        'Activated' => false,
        'Flags' => [
          'key' => 'value',
        ],
      ],
      1 => [
        'CampaignId' => 'xxxxxxxxxxxxxxxxxxxx',
        'VariationGroupId' => 'xxxxxxxxxxxxxxxxxxxx',
        'VariationId' => 'xxxxxxxxxxxxxxxxxxxx',
        'IsReference' => false,
        'Type' => '',
        'Activated' => false,
        'Flags' => [
          'myAwesomeFeature' => 20,
        ],
      ],
    ],
  ],
]
Example
<?php

require_once __DIR__ . '/vendor/autoload.php';


use Flagship\Cache\IVisitorCacheImplementation;
use Flagship\Config\FlagshipConfig;
use Flagship\Flagship;


/**
 * Implementing visitor caches with redis
 */
class VisitorCacheRedis implements IVisitorCacheImplementation{

    private $redis;
    public function __construct($address, $port)
    {
        $this->redis = new Redis();
        $this->redis->connect($address, $port);
    }

    public function cacheVisitor($visitorId, array $data)
    {
        $this->redis->set($visitorId, json_encode($data, JSON_NUMERIC_CHECK));
    }

    public function lookupVisitor($visitorId)
    {
        $data = $this->redis->get($visitorId);
        if (!$data){
            return null;
        }
        return json_decode($data, true);
    }

    public function flushVisitor($visitorId)
    {
      $this->redis->del($visitorId);
    }
}

Flagship::start("your_env_id", "your_api_key",
    FlagshipConfig::bucketing("http://127.0.0.1:8080/bucketing") // set the sync-agent endpoint URL
    ->setVisitorCacheImplementation(new VisitorCacheRedis("127.0.0.1", 6379)) // set visitor cache implementation 
);

$visitor = Flagship::newVisitor("visitorID")
        ->withContext(["plan"=>"enterprise"])
        ->build();

$visitor->fetchFlags();

$flag = $visitor->getFlag("your_flag_key", "default_value") ;
echo "value: ". $flag->getValue()."\n";
echo "exists: ". $flag->exists()."\n";
echo "metadata: ". json_encode($flag->getMetadata());

API reference

Flagship class

Visitor class

Flag class

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 NameDescriptionContext variable nameTypeAuto-set by SDKExample
FlagshipContext::DEVICE_LOCALELanguage of the devicesdk_deviceLanguageStringNofra
FlagshipContext::DEVICE_TYPEType of the devicesdk_deviceTypeDeviceTypeNoMobile
FlagshipContext::DEVICE_MODELModel of the devicesdk_deviceModelStringNosamsung E1200
FlagshipContext::LOCATION_CITYCity geolocationsdk_cityStringNotoulouse
FlagshipContext::LOCATION_REGIONRegion geolocationsdk_regionStringNooccitanie
FlagshipContext::LOCATION_COUNTRYCountry geolocationsdk_countryStringNoFrance
FlagshipContext::LOCATION_LATCurrent Latitudesdk_latDoubleNo43.623647
FlagshipContext::LOCATION_LONGCurrent Longitudesdk_longDoubleNo1.445397
FlagshipContext::IPIP of the devicesdk_ipStringNo127.0.0.1
FlagshipContext::OS_NAMEName of the OSsdk_osNameStringYESubuntu / centos
FlagshipContext::OS_VERSION_NAMEVersion name of the OSsdk_osVersionNameStringNo9.0.0
FlagshipContext::OS_VERSION_CODEVersion code of the OSsdk_osVersionCodeNumberNo24
FlagshipContext::CARRIER_NAMEName of the carrier or mobile virtual network operatorsdk_carrierNameStringNofree
FlagshipContext::INTERNET_CONNECTIONWhat is the internet connectionsdk_internetConnectionStringNo5g
FlagshipContext::APP_VERSION_NAMEVersion name of the appsdk_versionNameStringNo1.1.2-beta
FlagshipContext::APP_VERSION_CODEVersion code of the appsdk_versionCodeNumberNo40
FlagshipContext::INTERFACE_NAMEName of the interfacesdk_interfaceNameStringNoProductPage
FlagshipContext::FLAGSHIP_CLIENTFlagship SDK client (Reserved)fs_clientStringYesPHP
FlagshipContext::FLAGSHIP_VERSIONVersion of the Flagship SDK (Reserved)fs_versionStringYes2.0.0

Did this page help you?