Flagship class

The Flagship class represents the SDK. It facilitates the initialization process and creation of new visitors.

start method

Start the flagship SDK

  • public static function start(string $envId, string $apiKey, ?FlagshipConfig $config = null)

Arguments:

NameTypeRequiredDescription
envIdStringRequiredEnvironment id provided by Flagship.
apiKeyStringRequiredApi authentication key provided by Flagship.
config\Flagship\Config\DecisionApiConfig
\Flagship\Config\BucketingConfig
OptionalCustom flagship configuration. see SDK configuration

Example:

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

use Flagship\Flagship;

Flagship::start("<ENV_ID>", "<API_KEY>");

newVisitor method

Initialize the builder for visitor creation, and Return a VisitorBuilder instance.

  • public static function newVisitor(string $visitorId, bool $hasConsented) : \Flagship\Visitor\VisitorBuilder

Arguments:

NameTypeDescription
visitorIdstringUnique visitor identifier. If null is given, the SDK generates one by default.
hasConsentedboolRequired
Specifies if the visitor has consented for personal data usage.
When set to false, some features will be deactivated and the cache will be deactivated and cleared.

Example:

use Flagship\Flagship;

Flagship::start("<ENV_ID>", "<API_KEY>");

$visitor = Flagship::newVisitor("your_visitor_id")
              ->withContext(["age" => 31, "isVip" => true])
              ->build();

close method

This method batches and sends all collected hits. It should be called when your application (script) is about to terminate or in the event of a crash to ensures that all collected data is sent and not lost.

  • public static function Flagship::close(): void

getConfig method

Return the current config used by the SDK. see configuration

  • public static function Flagship::getConfig(): FlagshipConfig

getStatus method

Return current status of Flagship SDK.

  • public static function Flagship::getStatus(): FSSdkStatus

List of possible Flagship\Enum\FSSdkStatus:

StatustypevalueDescription
FSSdkStatus::SDK_NOT_INITIALIZEDint0It is the default initial status. This status remains until the sdk has been initialized successfully.
FSSdkStatus::SDK_INITIALIZINGint1The SDK is currently initializing.
FSSdkStatus::SDK_PANICint2Flagship SDK is ready but is running in Panic mode: All features are disabled except the one which refresh this status.
FSSdkStatus::SDK_INITIALIZEDint3The Initialization is done, and Flagship SDK is ready to use.

FlagshipConfig class

This class represents the configuration for the Flagship SDK. It provides methods to set and retrieve various configuration options.

decisionApi method

Initialize the SDK to start in Decision-Api mode

When the SDK is running in DecisionApi mode, the campaign assignments and targeting validation take place server-side in the flagship infrastructure. In this mode, each call to the fetchFlags method to refresh the flags will make an HTTP request.

  • public static function FlagshipConfig::decisionApi() : Flagship\Config\DecisionApiConfig

Example:

//Start sdk in Decision api mode.

use Flagship\Flagship;
use Flagship\Config\FlagshipConfig;

$config = FlagshipConfig::decisionApi();

Flagship::start("<ENV_ID>", "<API_KEY>", $config);

bucketing method

Initialize the SDK to start in 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.

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

Arguments:

NameTypeDescription
syncAgentUrlstringflagship-sync-agent endpoint URL

Example:

//Start sdk in Bucketing mode.

use Flagship\Flagship;
use Flagship\Config\FlagshipConfig;

$config = FlagshipConfig::bucketing("http://127.0.0.1:8080/bucketing");

Flagship::start("<ENV_ID>", "<API_KEY>", $config);

setCacheStrategy accessor

Define the strategy that will be used for hit batching with tracking manager.

The SDK allows you to send hits with a batching system. The advantage of batch processing with the TrackingManager is to use less network traffic, avoid loss of hits with cache, and catch all hits that would failed and resend them.

  • public function setCacheStrategy(CacheStrategy $cacheStrategy):\Flagship\Config\FlagshipConfig

Argument:

NameTypeDefault valueDescription
cacheStrategyint1Cache strategy.

List of possible Flagship\Enum\CacheStrategy :

KeyTypevalueDescription
CacheStrategy::BATCHING_AND_CACHING_ON_FAILUREint1[Recommended] When a hit is emitted, it will first be added into the pool, then batched and sent when the method Flagship::close() is called. If the batch send failed all hits inside will be cached in database using IHitCacheImplementation.

see example using redis
CacheStrategy::NO_BATCHING_AND_CACHING_ON_FAILUREint2When a hit is emitted, it will be sent directly. If the hit sending failed, it will be cached in database using IHitCacheImplementation.

Hits are sent as they are emitted.

Note: This strategy uses a little more network traffic than the first because each hit emitted will send an http request.

πŸ“˜

Information

Whenever your application (script) is about to terminate or in the event of a crash, you should call the Flagship::close() method to ensures that all the collected data is sent and not lost.

Example

use Flagship\Config\FlagshipConfig;
use Flagship\Enum\CacheStrategy;

$config = FlagshipConfig::decisionApi()
    ->setCacheStrategy(CacheStrategy::BATCHING_AND_CACHING_ON_FAILURE);

Flagship::start("<ENV_ID>", "<API_KEY>", $config);

//Create visitor
//Get your flag 
//Send your hits
//Do your stuff 

//Call before terminating 
Flagship::close();

setLogManager accessor

Specify a custom implementation of LogManager in order to receive logs from the SDK.

  • public function setLogManager(Psr\Log\LoggerInterface $logManager) : Flagship\Config\FlagshipConfig

Argument:

NameTypeDescription
logManagerPsr\Log\LoggerInterfaceCustom implementation of LogManager.

setLogLevel accessor

This accessor specifies the maximum log level to display..

  • public function setLogLevel(LogLevel $logLevel) : \Flagship\Config\FlagshipConfig

Argument:

NameTypeDescription
levelintValue from 0 to 9 check \Flagship\Enum\LogLevel

Here are the logs informations you'll have for each levels Flagship\\Enum\\LogLevel

KeyValueTypeDescription
LogLevel::NONE0intLogging will be disabled.
LogLevel::EMERGENCY1intOnly emergencies will be logged
LogLevel::ALERT2intOnly alerts and above will be logged.
LogLevel::CRITICAL3intOnly critical and above will be logged.
LogLevel::ERROR4intOnly errors and above will be logged.
LogLevel::WARNING5intOnly warnings and above will be logged.
LogLevel::NOTICE6intOnly notices and above will be logged.
LogLevel::INFO7intOnly info logs and above will be logged.
LogLevel::DEBUG8intOnly debug logs and above will be logged.
LogLevel::ALL9intEverything will be logged.

setTimeout accessor

Specify timeout in millisecond for api request.

  • public function setTimeout(int $timeout) : \Flagship\Config\FlagshipConfig

Argument:

NameTypeDescription
timeoutintTime in milliseconds. Default is 2000ms.

setFetchThirdPartyData accessor (Bucketing mode only)

If true, the SDK will fetch the visitor's segment from the universal data connector each time fetchFlags is called and append those segments in the visitor context.

  • public function setFetchThirdPartyData(bool $fetchThirdPartyData): \Flagship\Config\FlagshipConfig

Argument:

NameTypeDefaultDescription
fetchThirdPartyDataboolfalsevalue

setOnVisitorExposed accessor

Specify a callback function to be called each time a flag has been exposed to a visitor (i.e., when an activation hit is sent by the SDK).

  • public function setOnVisitorExposed(callable $onVisitorExposed) \Flagship\Config\FlagshipConfig

Argument:

NameTypeDescription
onVisitorExposedcallableCallback to trigger when a Flag has been exposed to a visitor and succeed.
It is triggered with 2 arguments: ExposedVisitorInterface and ExposedFlagInterface

Here is an example on how to use this callback:

Example with Mixpanel integration
Example with Segment integration

setOnSdkStatusChanged accessor

Define a callable function to get callback when the SDK status has changed. See SDK status section.

  • public function setOnSdkStatusChanged(callable $onSdkStatusChanged) \Flagship\Config\FlagshipConfig

Argument:

NameTypeDescription
onSdkStatusChangedcallableCallback to trigger when SDK status has changed.

setVisitorCacheImplementation accessor

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

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

Argument:

NameTypeDescription
visitorCacheImplementationFlagship\Cache\IVisitorCacheImplementationimplementation of IVisitorCacheImplementation interface

setHitCacheImplementation accessor

Define an object that implement the interface IHitCacheImplementation to handle hits cache.
see cache-manager

  • public function setHitCacheImplementation(IHitCacheImplementation $hitCacheImplementation) : \Flagship\Config\FlagshipConfig

Argument:

NameTypeDescription
hitCacheImplementationFlagship\Cache\IHitCacheImplementationimplementation of IHitCacheImplementation interface

setDisableDeveloperUsageTracking accessor

Determines whether to disable the collection of analytics data.

  • public function setDisableDeveloperUsageTracking(bool $disableDeveloperUsageTracking ): \Flagship\Config\FlagshipConfig

Argument:

NameTypeDefault valueDescription
disableDeveloperUsageTrackingboolfalseif set true no usage data will be collected

setSyncAgentUrl accessor (Bucketing mode only)

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

  • public function setBucketingUrl(string $syncAgentUrl): \Flagship\Config\BucketingConfig
NameTypeDescription
syncAgentUrlstringflagship-sync-agent endpoint URL

VisitorBuilder class

\Flagship\Visitor\VisitorBuilder is a fluent interface builder api managing Visitor creation.

setIsAuthenticated method

Specify whether the Visitor is authenticated or anonymous.

  • public function isAuthenticated(bool $isAuthenticated) : \Flagship\Visitor\VisitorBuilder

Argument:

NameTypeDescription
isAuthenticatedbooltrue for an authenticated visitor, false for an anonymous visitor.

setContext method

Specify Visitor initial context key / values used for targeting.

  • public function setContext(array $context) : \Flagship\Visitor\VisitorBuilder

Argument:

NameTypeDescription
withContextarray (associative array)visitor initial context.
e.g: ["age"=>42, "IsVip"=>true, "country"=>"UK"].
Note:

- Visitor context keys must have a type of string
- Visitor context values must have a type of string, bool, numeric
- Visitor context keys and values are case sensitive

setOnFetchFlagsStatusChanged method

Specify a callback function to be called when the status of the fetchFlags method changes.

  • public function onFetchFlagsStatusChanged(callable $onFetchFlagsStatusChanged): \Flagship\Visitor\VisitorBuilder

Argument:

NameTypeDescription
onFetchFlagsStatusChangedcallableFunction callback.
The callback function should have the following signature:
function(FetchFlagsStatusInterface $fetchFlagsStatus): void.
see the FetchFlagsStatusInterface

build method

It completes the Visitor Creation process and returns an instance of \Flagship\Visitor\VisitorInterface

  • public function build() : \Flagship\Visitor\Visitor

Example


use Flagship\Flagship;
use Flagship\Model\FetchFlagsStatusInterface;

$visitor = Flagship::newVisitor(null, true)
    ->setContext(["age" => 31, "isVip" => true])
    ->onFetchFlagsStatusChanged(function (FetchFlagsStatusInterface $status) {
        // 
    })->build();

VisitorInterface

The VisitorInterface interface represents a unique user within your application. It aids in managing the visitor's data and fetching the corresponding flags for the visitor from the Flagship platform .

getVisitorId getter

The unique visitor identifier.

  • public function getVisitorId() : string

getAnonymousId getter

Visitor anonymous id

  • public function getAnonymousId(): string

hasConsented getter

It returns True if the visitor has consented for private data usage, otherwise return False.

  • public function hasConsented(): boolean

setConsent setter

Set if visitor has consented for protected data usage.

  • public function setConsent(boolean $hasConsented): void

getContext getter

Get the current visitor's context

  • function getContext(): array

setContext setter

Clear the current context and set a new context value

  • public function setContext(array $context)

clearContext method

Clear the visitor's context

public function clearContext() : void

getFetchStatus getter

The fetch status of the flags. see the FetchFlagsStatusInterface

  • public function getFetchStatus(): FetchFlagsStatusInterface;

getFlagsDTO method

Return an array of all flags data fetched for the current visitor.

  • public function getFlagsDTO(): FlagDTO[]

updateContext method

Update the visitor context values, matching the given keys, used for targeting. If the key doesn't exist in the visitor's context, it will be added.

  • public function updateContext(string $key, bool|numeric|string $value) : void

Arguments:

NameTypeDescription
keyStringContext key.
Note:

- Visitor context keys must have a type of string
valuebool or numeric or stringContext value.
Note:

- Visitor context values must have a type of string, bool, numeric
- Visitor context keys and values are case sensitive

updateContextCollection method

Update the visitor context values, matching the given keys, used for targeting. If the key doesn't exist in the visitor's context, it will be added.

  • public function updateContextCollection(array $Context) : void

Argument:

NameTypeDescription
contextarray (associative array)collection of keys, values. e.g: ["age"=>42, "IsVip"=>true, "country"=>"UK"]
Note:

- Visitor context keys must have a type of string
- Visitor context values must have a type of string, bool, numeric
- Visitor context keys and values are case sensitive

Context with predefined keys of context

Here's an example of how to use these predefined keys to update the visitor context in both Node.js and Deno environments:

use Flagship\Flagship;
use Flagship\Enum\FlagshipContext;

Flagship::start("<ENV_ID>", "<API_KEY>");
$visitor = Flagship::newVisitor("your_visitor_id", true)
              ->context(["age" => 31, "isVip" => true])
              ->build();

$visitor->updateContext(FlagshipContext::OS_NAME, "linux");
$visitor->updateContext(FlagshipContext::IP, "127.0.0.1");

Here is the List of all predefined context keys.

fetchFlags method

Invokes the decision API or refers to the bucketing file to refresh all campaign flags based on the visitor's context.

  • public function fetchFlags() : void

Example:

use Flagship\Flagship;

Flagship::start("<ENV_ID>", "<API_KEY>");

$visitor = Flagship::newVisitor("your_visitor_id", true)->build();

$visitor->fetchFlags();

getFlag method

Returns an instance of FlagInterface by its key. If no flag matches the given key, an empty flag will be returned. the exists() method of the FlagInterface object can be called to check if the flag has been found.

  • public function getFlag(string $key) : \Flagship\Flag\FlagInterface
ArgumentTypeDescription
keystringKey associated to the flag

Example:

use Flagship\Flagship;

Flagship::start("<ENV_ID>", "<API_KEY>");

$visitor = Flagship::newVisitor("your_visitor_id", true)->build();

$visitor->fetchFlags();

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

authenticate method

Authenticates anonymous visitor

  • public function authenticate(string $visitorId) : void
ParameterTypeDescription
visitorIdstringId of the new authenticated visitor.

πŸ“˜

Information

  • It is recommended calling the fetchFlags method just after authenticating a visitor as the visitor data has changed.
  • The visitor targeting / Flags could change based on this new data.

unauthenticate method

This method changes authenticated Visitor to anonymous visitor.

  • public function unauthenticate() : void

πŸ“˜

Information

  • It is recommended calling the fetchFlags method just after authenticating a visitor as the visitor data has changed.
  • The visitor targeting / Flags could change based on this new data.

sendHit method

This method sends Hits to the Flagship servers for reporting.

  • public function sendHit(HitAbstract $hit) : void
ParameterTypeDescription
hitHitAbstractHit to send.

Example:

use Flagship\Flagship;
use Flagship\Hit\Page;

$visitor = Flagship::newVisitor("your_visitor_id", true)->build();

$visitor->sendHit(new Page("https://www.my_domain_com/my_page"));

FlagInterface

This interface represents a flag in the Flagship SDK. It helps you retrieve the flag value, access flag metadata, expose the flag, verify the flag's existence, and get the flag status with the following API:

getValue method

Returns the value of the flag if the flag exists and the type of the default value matches the flag type value, otherwise it returns the default value.

  • public function getValue(bool $visitorExposed, bool|numeric|string|null|array $defaultValue) : bool|numeric|string|null|array

Argument:

NameTypeDefault ValueDescription
defaultValuebool|numeric|string|array|nullRequiredFlag default value
Note: Default value must be one of the following type : string, bool, numeric, array. null
visitorExposedbooltrueIndicates to Flagship that the visitor have been exposed and have seen this flag. This will increment the visits for the current variation on your campaign reporting.
It is possible to set this param to false and call the visitorExposed() method afterward when the visitor sees it.

Example:

use Flagship\Flagship;

Flagship::start("<ENV_ID>", "<API_KEY>");

$visitor = Flagship::newVisitor("your_visitor_id", true)->build();

$visitor->fetchFlags();

$flagValue = $visitor->getFlag("displayVipFeature")->getValue(false);

getMetadata method

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

  • public function getMetadata() : FlagMetadata

The FlagMetadata class has the following shape:

gettersTypeDescription
getCampaignIdstringCampaign ID
getCampaignNamestringCampaign name
getVariationGroupIdstringVariation group ID
getVariationGroupNamestringVariation group name
getVariationIdstringThe variation ID assigned to the visitor
getVariationNamestringVariation name
getIsReferencebooleanSpecify if its the reference variation
getCampaignTypestringcampaign type
getSlugstringcampaign slug

visitorExposed method

Notifies Flagship that the visitor has been exposed to and seen this flag.

  • public function visitorExposed() : void

exists method

This method checks if the flag exists.

  • public function exists() : bool

getStatus method

Returns the status of the flag.

  • public function getStatus(): FSFlagStatus

List of possible Flagship\Enum\FSFlagStatus:

StatustypevalueDescription
FSFlagStatus::FETCHEDint0The flags have been successfully fetched from the API or re-evaluated in bucketing mode.
FSFlagStatus::FETCH_REQUIREDint1The flags need to be re-fetched due to a change in context, or because the flags were loaded from cache or XPC.
FSFlagStatus::NOT_FOUNDint2The flag was not found or do not exist.
FSFlagStatus::PANICint3The SDK is in PANIC mode: All features are disabled except for the one to fetch flags.

FSFlagCollectionInterface

It represents a collection of flags.

getSize method

Gets the number of flags in the collection.

  • public function getSize(): int

get method

It returns the flag associated with the specified key, or an empty if the key is not found.

  • public function get(string $key): FSFlagInterface

Arguments:

NameTypeDescription
keyStringThe key associated to the flag.

has method

Checks if the collection contains a flag with the specified key.

  • public function has(string $key): bool

Arguments:

NameTypeDescription
keyStringThe key associated to the flag.

keys method

Gets the keys of all flags in the collection.

  • public function keys(): array

filter method

It filters the collection based on a predicate function and returns A new FSFlagCollectionInterface containing the flags that satisfy the predicate.

  • public function filter(callable $predicate): FSFlagCollectionInterface

Arguments:

NameTypeDescription
predicatefunctionA function that accepts three parameters:

- FSFlagInterface $flag - The current flag being processed.string $key
- The key of the current flag.
- FSFlagCollectionInterface $collection - The collection the flag belongs to.

exposeAll method

Exposes all flags in the collection.

  • public function exposeAll(): void

getMetadata method

Retrieves the metadata for all flags in the collection.

  • public function getMetadata(): array

toJSON method

Serializes the metadata for all flags in the collection.

  • public function toJSON(): string

each method

Iterates over each flag in the collection.

Arguments:

NameTypeDescription
predicatefunctionA function that accepts three parameters:

- FSFlagInterface $flag - The current flag being processed.string $key
- string $key of the current flag.
- FSFlagCollectionInterface $collection - The collection the flag belongs to.

Hit Tracking

This section guides you on how to track visitors in your application and learn how to build hits to feed your reports. For more details about our measurement protocol, refer to our Universal Collect documentation.

There are five different types of Hits:

  • Page
  • Screen
  • Transaction
  • Item
  • Event

Common Optional Parameters for Hits

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
setUserIpStringVisitor IP
setScreenResolutionstringScreen resolution.
setLocaleStringvisitor language
setSessionNumberstringSession number

Page hit

This hit should be sent each time a visitor navigates to a new page.

Constructor:

new Page(string $pageUrl)

Arguments:

NameTypeDescription
pageUrlStringValid url.

Example:

use Flagship\Hit\Page;

$page = new Page("https://www.my_domain_com/my_page");

$visitor->sendHit($page);

Transaction hit

This hit should be sent when a visitor completes a Transaction.

Constructor:

new Transaction(string $transactionId, string $affiliation)

Arguments:

NameTypeDescription
transactionIdStringUnique identifier for your transaction.
affiliationStringThe name of the KPI that you will have inside your reporting. Learn more

A hit of type TRANSACTION has this following structure:

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

Example:

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

Item hit

This hit is used to associate an item with a transaction. It should be sent following the corresponding transaction hit.

Constructor:

new Item(string $transactionId, string $productName, string $productSku)

Arguments:

NameTypeDescription
transactionIdStringUnique identifier for your transaction.
productNameStringName of your item.
productSkuStringSpecifies the SKU or item code.

A hit of type ITEM has this following structure:

Builder ParameterTypeDescription
setItemCategoryStringSpecifies the category that the item belongs to.
setItemPricefloatSpecifies the price for a single item/unit.
setItemQuantityintSpecifies the number of items purchased.

Example:

use Flagship\Hit\Item;

$item = (new Item("#12345", "product", "sku123"))
            ->setItemCategory("test")
            ->setItemPrice(199.99)
            ->setItemQuantity(1);

$visitor->sendHit($item);

πŸ“˜

Information

The Item hit is not currently available in the Flagship reporting view.

Event hit

This hit can be used to track any event, such as a click on 'Add To Cart' or a newsletter subscription.

public Event(EventCategory category, String action)

Argument:

NameTypeDescription
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

An EVENT type hit has the following structure:

Builder ParameterTypeDescription
setLabelString(optional) Additional description of your event.
setValueInteger(optional) Can be used to evaluate visitor interactions with individual site objects or content items.
NOTE: this value must be non-negative / non-float

Example:

use Flagship\Hit\Event;

$event = (new Event(EventCategory::USER_ENGAGEMENT, "action"))
              ->setLabel("label")
              ->setValue(100);

$visitor->sendHit($event);

Cache management

The purpose of cache management is to address the following issues:

  • Re-allocation in bucketing mode :

In bucketing mode and with the cache enabled, the SDK will always keep visitor in the variation to which 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 IVisitorCacheImplementation interface which defines the methods that an object must implement to manager it.

<?php

namespace Flagship\Cache;

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

    public function lookupVisitor($visitorId);

    public function flushVisitor($visitorId);
}

cacheVisitor method

This method is invoked when the SDK needs to store visitor information in your database.

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

Arguments:

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

lookupVisitor method

This method is invoked when the SDK needs to retrieve visitor information associated with a specific visitor ID from your database.

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

  • public function lookupVisitor($visitorId) : array

Argument :

NameTypeDescription
visitorIdstringvisitor ID

flushVisitor method

This method is invoked when the SDK needs to delete the visitor information associated with a specific visitor ID from your database.

It will be called every time setConsent get false.

  • public function flushVisitor($visitorId) : void

Argument :

NameTypeDescription
visitorIdstringvisitor ID

πŸ“˜

Information

  • 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("<ENV_ID>", "<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());

Hit Cache

The hit cache is used to store hits in your database based on the strategy used through the IHitCacheImplementation interface which defines the methods that an object must implement to handle it.

<?php

namespace Flagship\Cache;

interface IHitCacheImplementation
{
    public function cacheHit(array $hits);

    public function lookupHits();

    public function flushHits(array $hitKeys);

    public function flushAllHits();
}

cacheHit method

This method will be called to cache hits depending on cache strategy used.

  • public function cacheHit(array $hits):void

Argument :

NameTypeDescription
hitsarrayit's an associative array where the :

- key is a unique ID for each hit
- value is an array that follows the shape of type HitCacheDTO.

lookupHits method

This method will be called to load all hits from your database and trying to send them again when Flagship::close().

It has to return an associative array where the key is a unique ID for each hit and the value is an array which follows this shape see.

  • public function lookupHits():array

flushHits method

This method will be called to erase all hits matching the unique Hits ID from your database.

NOTE: It will be called every time setConsent get false to erase all hits from database for visitor who set consent to false.

  • public function flushHits(array $hitKeys):void

Argument :

NameTypeDescription
hitKeysArrayUnique ID of hits

flushAllHits function

This method will be called to erase all hits in your database without exception.

  • public function flushAllHits():void

HitCacheDTO

[
    'visitorId:Guid' => [
        'version' => 1,
        'data' => [
            'visitorId' => 'visitorId',
            'anonymousId' => NULL,
            'type' => 'ACTIVATE',
            'content' => [
                'variationGroupId' => 'xxxxxxxxxxxxxxx',
                'variationId' => 'xxxxxxxxxxxxxxxx',
                'visitorId' => 'visitorId',
                'ds' => 'APP',
                'type' => 'ACTIVATE',
                'anonymousId' => NULL,
                'userIP' => NULL,
                'pageResolution' => NULL,
                'locale' => NULL,
                'sessionNumber' => NULL,
                'key' => 'visitorId:Guid',
                'createdAt' => 1676542078044,
            ],
            'time' => 1676542078045,
        ],
    ]
]

πŸ“˜

Information

  • flushHits method will be called every time setConsent get false.
  • Hits older than 4H will be ignored during the resending process.

Sample implementation of IHitCacheImplementation interface using redis

use Flagship\Cache\IHitCacheImplementation;

class HitCacheRedis implements IHitCacheImplementation
{

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

    /**
     * @inheritDoc
     */
    public function cacheHit(array $hits)
    {
        $redis = $this->redis->multi();
        foreach ($hits as $key => $hit) {
            $redis->set($key, json_encode($hit));
        }
        $redis->exec();
    }

    /**
     * @inheritDoc
     */
    public function lookupHits()
    {
        $keys = $this->redis->keys('*');
        $hits = $this->redis->mGet($keys);
        if (!$hits) {
            return [];
        }
        $hitsOut = [];
        foreach ($hits as $key => $hit) {
            $hitsOut[$keys[$key]] = json_decode($hit, true);
        }
        return $hitsOut;
    }

    /**
     * @inheritDoc
     */
    public function flushHits(array $hitKeys)
    {
        $this->redis->del($hitKeys);
    }

    public function flushAllHits()
    {
        $this->redis->flushDB();
    }
}

ExposedVisitorInterface

It's an interface to get information about the visitor to whom the flag has been exposed

<?php

namespace Flagship\Model;

interface ExposedVisitorInterface
{
    /**
     * Visitor id
     * @return string
     */
    public function getId(): string;

    /**
     * visitor anonymous id
     * @return string|null
     */
    public function getAnonymousId(): ?string;

    /**
     * visitor context
     * @return array<string, mixed>
     */
    public function getContext(): array;
}

ExposedFlagInterface

It's an interface to get information about the flag that has been exposed.

<?php

namespace Flagship\Model;

use Flagship\Flag\FSFlagMetadataInterface;

interface ExposedFlagInterface
{
    /**
     * Return the key of flag
     * @return string
     */
    public function getKey(): string;

    /**
     * Return the value of flag
     * @return float|array|bool|int|string|null
     */
    public function getValue(): float|array|bool|int|string|null;

    /**
     * Return the metadata of flag
     * @return FSFlagMetadataInterface
     */
    public function getMetadata(): FSFlagMetadataInterface;

    /**
     * Return the default value of flag
     * @return float|array|bool|int|string|null
     */
    public function getDefaultValue(): float|array|bool|int|string|null;
}

FetchFlagsStatusInterface

It Represents the status of visitor fetch for flag data.

<?php

namespace Flagship\Model;

use Flagship\Enum\FSFetchReason;
use Flagship\Enum\FSFetchStatus;

interface FetchFlagsStatusInterface
{
    /**
     * The new status of the flags fetch.
     *
     * @return FSFetchStatus
     */
    public function getStatus(): FSFetchStatus;

    /**
     * The reason for the status change
     *
     * @return FSFetchReason
     */
    public function getReason(): FSFetchReason;
}

List of possible Flagship\Enum\FSFetchStatus:

StatusTypeValueDescription
FSFetchStatus::FETCHEDint0The flags have been successfully fetched from the API or re-evaluated in bucketing mode.
FSFetchStatus::FETCHINGint1The flags are currently being fetched from the API or re-evaluated in bucketing mode.
FSFetchStatus::FETCH_REQUIREDint2The flags need to be re-fetched due to a change in context, or because the flags were loaded from cache or XPC.
FSFetchStatus::PANICint3The SDK is in PANIC mode: All features are disabled except for the one to fetch flags.

List of possible Flagship\Enum\FSFetchReason:

StatusTypeValueDescription
FSFetchReason::NONEint0Indicates that there is no specific reason for fetching flags.
FSFetchReason::VISITOR_CREATEDint1Indicates that the visitor has been created.
FSFetchReason::UPDATE_CONTEXTint2Indicates that a context has been updated or changed.
FSFetchReason::AUTHENTICATEint3Indicates that the XPC method 'authenticate' has been called.
FSFetchReason::UNAUTHENTICATEint4Indicates that the XPC method 'unauthenticate' has been called.
FSFetchReason::FETCH_ERRORint5Indicates that fetching flags has failed.
FSFetchReason::FLAGS_FETCHED_FROM_CACHEint6Indicates that flags have been fetched from the cache.

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

Predefined visitor context keys

The Flagship SDK contains predefined visitor 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.

All possible predefined keys are listed below:

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

πŸ“˜

Information

To overwrite the keys, use the updateContext method