Reference
Flagship
class
Flagship
classThe Flagship
class represents the SDK. It facilitates the initialization process and creation of new visitors.
start
method
start
methodStart the flagship SDK
public static function start(string $envId, string $apiKey, ?FlagshipConfig $config = null)
Arguments:
envId
String
Required
Environment id provided by Flagship.
apiKey
String
Required
Api authentication key provided by Flagship.
config
\Flagship\Config\DecisionApiConfig \Flagship\Config\BucketingConfig
Optional
Custom flagship configuration. see SDK configuration
Example:
require __DIR__ . '/vendor/autoload.php';
use Flagship\Flagship;
Flagship::start("<ENV_ID>", "<API_KEY>");
newVisitor
method
newVisitor
methodInitialize the builder for visitor creation, and Return a VisitorBuilder
instance.
public static function newVisitor(string $visitorId, bool $hasConsented) : \Flagship\Visitor\VisitorBuilder
Arguments:
visitorId
string
Unique visitor identifier. If null
is given, the SDK generates one by default.
hasConsented
bool
Required 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
close
methodThis 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
getConfig
methodReturn the current config used by the SDK. see configuration
public static function Flagship::getConfig(): FlagshipConfig
getStatus
method
getStatus
methodReturn current status of Flagship SDK.
public static function Flagship::getStatus(): FSSdkStatus
List of possible Flagship\Enum\FSSdkStatus
:
FSSdkStatus::SDK_NOT_INITIALIZED
int
0
It is the default initial status. This status remains until the sdk has been initialized successfully.
FSSdkStatus::SDK_INITIALIZING
int
1
The SDK is currently initializing.
FSSdkStatus::SDK_PANIC
int
2
Flagship SDK is ready but is running in Panic mode: All features are disabled except the one which refresh this status.
FSSdkStatus::SDK_INITIALIZED
int
3
The Initialization is done, and Flagship SDK is ready to use.
FlagshipConfig
class
FlagshipConfig
classThis class represents the configuration for the Flagship SDK. It provides methods to set and retrieve various configuration options.
decisionApi
method
decisionApi
methodInitialize 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
bucketing
methodInitialize 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. SeeBucketing polling section.
public static function FlagshipConfig::bucketing(string $syncAgentUrl) : Flagship\Config\BucketingConfig
Arguments:
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
setCacheStrategy
accessorDefine 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:
cacheStrategy
int
1
Cache strategy.
List of possible Flagship\Enum\CacheStrategy
:
CacheStrategy::BATCHING_AND_CACHING_ON_FAILURE
int
1
[Recommended] When a hit is emitted, it will first be added into the pool, then batched and sent when the method Flagship::close()
is invoked. 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_FAILURE
int
2
When 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. This strategy uses a little more network traffic than the first because each hit emitted will send an HTTP request.
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
setLogManager
accessorSpecify a custom implementation of LogManager in order to receive logs from the SDK.
public function setLogManager(Psr\Log\LoggerInterface $logManager) : Flagship\Config\FlagshipConfig
Argument:
logManager
Psr\Log\LoggerInterface
Custom implementation of LogManager.
setLogLevel
accessor
setLogLevel
accessorThis accessor specifies the maximum log level to display..
public function setLogLevel(LogLevel $logLevel) : \Flagship\Config\FlagshipConfig
Argument:
level
int
Value from 0
to 9
check \Flagship\Enum\LogLevel
Here are the logs informations you'll have for each levels Flagship\\Enum\\LogLevel
LogLevel::NONE
0
int
Logging will be disabled.
LogLevel::EMERGENCY
1
int
Only emergencies will be logged
LogLevel::ALERT
2
int
Only alerts and above will be logged.
LogLevel::CRITICAL
3
int
Only critical and above will be logged.
LogLevel::ERROR
4
int
Only errors and above will be logged.
LogLevel::WARNING
5
int
Only warnings and above will be logged.
LogLevel::NOTICE
6
int
Only notices and above will be logged.
LogLevel::INFO
7
int
Only info logs and above will be logged.
LogLevel::DEBUG
8
int
Only debug logs and above will be logged.
LogLevel::ALL
9
int
Everything will be logged.
setTimeout
accessor
setTimeout
accessorSpecify timeout in millisecond for api request.
public function setTimeout(int $timeout) : \Flagship\Config\FlagshipConfig
Argument:
timeout
int
Time in milliseconds. Default is 2000ms.
setFetchThirdPartyData
accessor (Bucketing mode only)
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:
fetchThirdPartyData
bool
false
value
setOnVisitorExposed
accessor
setOnVisitorExposed
accessorSpecify 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:
onVisitorExposed
callable
Callback 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
setOnSdkStatusChanged
accessorDefine 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:
onSdkStatusChanged
callable
Callback to trigger when SDK status has changed.
setVisitorCacheImplementation
accessor
setVisitorCacheImplementation
accessorDefine an object that implement the interface IVisitorCacheImplementation to handle the visitor cache. see cache-manager
public function setVisitorCacheImplementation(IVisitorCacheImplementation $visitorCacheImplementation) : \Flagship\Config\FlagshipConfig
Argument:
visitorCacheImplementation
Flagship\Cache\IVisitorCacheImplementation
implementation of IVisitorCacheImplementation interface
setHitCacheImplementation
accessor
setHitCacheImplementation
accessorDefine an object that implement the interface IHitCacheImplementation to handle hits cache. see cache-manager
public function setHitCacheImplementation(IHitCacheImplementation $hitCacheImplementation) : \Flagship\Config\FlagshipConfig
Argument:
hitCacheImplementation
Flagship\Cache\IHitCacheImplementation
implementation of IHitCacheImplementation interface
setDisableDeveloperUsageTracking
accessor
setDisableDeveloperUsageTracking
accessorDetermines whether to disable the collection of analytics data.
public function setDisableDeveloperUsageTracking(bool $disableDeveloperUsageTracking ): \Flagship\Config\FlagshipConfig
Argument:
disableDeveloperUsageTracking
bool
false
if set true no usage data will be collected
setSyncAgentUrl
accessor (Bucketing mode only)
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
syncAgentUrl
string
flagship-sync-agent endpoint URL
VisitorBuilder
class
VisitorBuilder
class\Flagship\Visitor\VisitorBuilder
is a fluent interface builder api managing Visitor creation.
setIsAuthenticated
method
setIsAuthenticated
methodSpecify whether the Visitor is authenticated or anonymous.
public function isAuthenticated(bool $isAuthenticated) : \Flagship\Visitor\VisitorBuilder
Argument:
isAuthenticated
bool
true for an authenticated visitor, false for an anonymous visitor.
setContext
method
setContext
methodSpecify Visitor initial context key / values used for targeting.
public function setContext(array $context) : \Flagship\Visitor\VisitorBuilder
Argument:
withContext
array (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
setOnFetchFlagsStatusChanged
methodSpecify a callback function to be called when the status of the fetchFlags method changes.
public function onFetchFlagsStatusChanged(callable $onFetchFlagsStatusChanged): \Flagship\Visitor\VisitorBuilder
Argument:
onFetchFlagsStatusChanged
callable
Function callback.
The callback function should have the following signature:
function(FetchFlagsStatusInterface $fetchFlagsStatus): void
.
See the FetchFlagsStatusInterface.
build
method
build
methodIt 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
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
getVisitorId
getterThe unique visitor identifier.
public function getVisitorId() : string
getAnonymousId
getter
getAnonymousId
getterVisitor anonymous id
public function getAnonymousId(): string
hasConsented
getter
hasConsented
getterIt returns True if the visitor has consented for private data usage, otherwise return False.
public function hasConsented(): boolean
setConsent
setter
setConsent
setterSet if visitor has consented for protected data usage.
public function setConsent(boolean $hasConsented): void
getContext
getter
getContext
getterGet the current visitor's context
function getContext(): array
setContext
setter
setContext
setterClear the current context and set a new context value
public function setContext(array $context)
clearContext
method
clearContext
methodClear the visitor's context
public function clearContext() : void
getFetchStatus
getter
getFetchStatus
getterThe fetch status of the flags. see the FetchFlagsStatusInterface
public function getFetchStatus(): FetchFlagsStatusInterface;
getFlagsDTO
method
getFlagsDTO
methodReturn an array of all flags data fetched for the current visitor.
public function getFlagsDTO(): FlagDTO[]
updateContext
method
updateContext
methodUpdate 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:
key
String
Context key.
Note:
• Visitor context keys must have a type of string
.
value
bool or numeric or string
Context value.
Note:
• Visitor context values must have a type of string
, bool
, numeric
.
• Visitor context keys and values are case sensitive.
updateContextCollection
method
updateContextCollection
methodUpdate 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:
context
array (associative array)
Collection of keys and 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
fetchFlags
methodInvokes 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
getFlag
methodReturns 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
key
string
Key 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
authenticate
methodAuthenticates anonymous visitor
public function authenticate(string $visitorId) : void
visitorId
string
Id of the new authenticated visitor.
unauthenticate
method
unauthenticate
methodThis method changes authenticated Visitor to anonymous visitor.
public function unauthenticate() : void
sendHit
method
sendHit
methodThis method sends Hits to the Flagship servers for reporting.
public function sendHit(HitAbstract $hit) : void
hit
HitAbstract
Hit 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
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
getValue
methodReturns 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:
defaultValue
bool | numeric | string | array | null
Required
Flag default value.
Default value must be one of the following types: string
, bool
, numeric
, array
, or null
.
visitorExposed
bool
true
Indicates to Flagship that the visitor has been exposed and has 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
getMetadata
methodReturns 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:
getCampaignId
string
Campaign ID
getCampaignName
string
Campaign name
getVariationGroupId
string
Variation group ID
getVariationGroupName
string
Variation group name
getVariationId
string
The variation ID assigned to the visitor
getVariationName
string
Variation name
getIsReference
boolean
Specify if its the reference variation
getCampaignType
string
campaign type
getSlug
string
campaign slug
visitorExposed
method
visitorExposed
methodNotifies Flagship that the visitor has been exposed to and seen this flag.
public function visitorExposed() : void
exists
method
exists
methodThis method checks if the flag exists.
public function exists() : bool
getStatus
method
getStatus
methodReturns the status of the flag.
public function getStatus(): FSFlagStatus
List of possible Flagship\Enum\FSFlagStatus
:
FSFlagStatus::FETCHED
int
0
The flags have been successfully fetched from the API or re-evaluated in bucketing mode.
FSFlagStatus::FETCH_REQUIRED
int
1
The flags need to be re-fetched due to a change in context, or because the flags were loaded from cache or XPC.
FSFlagStatus::NOT_FOUND
int
2
The flag was not found or do not exist.
FSFlagStatus::PANIC
int
3
The 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
getSize
methodGets the number of flags in the collection.
public function getSize(): int
get
method
get
methodIt returns the flag associated with the specified key, or an empty if the key is not found.
public function get(string $key): FSFlagInterface
Arguments:
key
String
The key associated to the flag.
has
method
has
methodChecks if the collection contains a flag with the specified key.
public function has(string $key): bool
Arguments:
key
String
The key associated to the flag.
keys
method
keys
methodGets the keys of all flags in the collection.
public function keys(): array
filter
method
filter
methodIt 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:
predicate
function
A 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
exposeAll
methodExposes all flags in the collection.
public function exposeAll(): void
getMetadata
method
getMetadata
methodRetrieves the metadata for all flags in the collection.
public function getMetadata(): array
toJSON
method
toJSON
methodSerializes the metadata for all flags in the collection.
public function toJSON(): string
each
method
each
methodIterates over each flag in the collection.
Arguments:
predicate
function
A 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.
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")
);
setUserIp
String
Visitor IP
setScreenResolution
string
Screen resolution.
setLocale
String
visitor language
setSessionNumber
string
Session number
Page hit
This hit should be sent each time a visitor navigates to a new page.
Constructor:
new Page(string $pageUrl)
Arguments:
pageUrl
String
Valid 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:
transactionId
String
Unique identifier for your transaction.
A hit of type TRANSACTION
has this following structure:
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.
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:
transactionId
String
Unique identifier for your transaction.
productName
String
Name of your item.
productSku
String
Specifies the SKU or item code.
A hit of type ITEM
has this following structure:
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.
Example:
use Flagship\Hit\Item;
$item = (new Item("#12345", "product", "sku123"))
->setItemCategory("test")
->setItemPrice(199.99)
->setItemQuantity(1);
$visitor->sendHit($item);
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:
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
An EVENT
type hit has the following structure:
setLabel
String
(optional) Additional description of your event.
setValue
Integer
(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
cacheVisitor
methodThis method is invoked when the SDK needs to store visitor information in your database.
public function cacheVisitor($visitorId, array $data) : void
Arguments:
visitorId
string
visitor ID
lookupVisitor
method
lookupVisitor
methodThis 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 :
visitorId
string
visitor ID
flushVisitor
method
flushVisitor
methodThis 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 :
visitorId
string
visitor ID
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
cacheHit
methodThis method will be called to cache hits depending on cache strategy used.
public function cacheHit(array $hits):void
Argument :
hits
array
It's an associative array where:
key – a unique ID for each hit
value – an array that follows the shape of type
HitCacheDTO
lookupHits
method
lookupHits
methodThis 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
flushHits
methodThis 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 :
hitKeys
Array<string>
Unique ID of hits
flushAllHits
function
flushAllHits
functionThis 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,
],
]
]
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
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
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
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
:
FSFetchStatus::FETCHED
int
0
The flags have been successfully fetched from the API or re-evaluated in bucketing mode.
FSFetchStatus::FETCHING
int
1
The flags are currently being fetched from the API or re-evaluated in bucketing mode.
FSFetchStatus::FETCH_REQUIRED
int
2
The flags need to be re-fetched due to a change in context, or because the flags were loaded from cache or XPC.
FSFetchStatus::PANIC
int
3
The SDK is in PANIC mode: All features are disabled except for the one to fetch flags.
List of possible Flagship\Enum\FSFetchReason
:
FSFetchReason::NONE
int
0
Indicates that there is no specific reason for fetching flags.
FSFetchReason::VISITOR_CREATED
int
1
Indicates that the visitor has been created.
FSFetchReason::UPDATE_CONTEXT
int
2
Indicates that a context has been updated or changed.
FSFetchReason::AUTHENTICATE
int
3
Indicates that the XPC method 'authenticate' has been called.
FSFetchReason::UNAUTHENTICATE
int
4
Indicates that the XPC method 'unauthenticate' has been called.
FSFetchReason::FETCH_ERROR
int
5
Indicates that fetching flags has failed.
FSFetchReason::FLAGS_FETCHED_FROM_CACHE
int
6
Indicates 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:
envId
string
Environment id provided by Flagship.
pollingInterval
int
Define time interval between two bucketing updates. Default is 2000ms.
Port
int
Endpoint listen port. Default is 8080
address
string
Address 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:
FS_ENV_ID
string
Environment id provided by Flagship.
FS_POLLING_INTERVAL
int
Define time interval between two bucketing updates. Default is 2000ms.
FS_PORT
int
Endpoint listen port. Default is 8080
FS_ADDRESS
string
Address where the endpoint is served. Default is 0.0.0.0
API docs
/bucketing
Get the Json bucketing file
/health_check
Return 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:
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
Last updated
Was this helpful?