PHP V1.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.

Feel free to contact us if you have any questions regarding this documentation.

SDK features

That SDK version helps you :

Prerequisites

  • Packagist PHP Version SupportPackagist PHP Version Support
  • 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");

Parameter

Type

Description

envId

String

Environment id provided by Flagship.

apiKey

String

Api authentication key provided by Flagship.

config

FlagshipConfig

(optional) Custom flagship configuration.

Flagship config

This class aims to help you to configure the SDK via the following optional methods:

use Flagship\FlagshipConfig;

$config = (new FlagshipConfig())
    ->setLogManager(new CustomLogManager())
    ->setLogLevel(Flagship\Enum\LogLevel::ALL)
    ->setTimeout(2000);

Flagship::start("your_env_id", "your_api_key", $config);

  • public function setLogManager(Psr\Log\LoggerInterface $logManager) : \Flagship\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\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\FlagshipConfig

    Specify timeout for api request.

Parameter

Type

Description

timeout

int

Milliseconds for connect and read timeouts. Default is 2000ms.



Create a new visitor


The \Flagship\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 by the Flagship Decision API 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", ["age" => 31, "isVip" => true]);

  • public static function newVisitor(string $visitorId, array $context) : \Flagship\Visitor

    Create a new visitor with a context. Return a new \Flagship\Visitor or null if the SDK hasn't started successfully.

Parameter

Type

Description

visitorId

String

Unique visitor identifier.

context

array (associative array)

(optional) Initial visitor context.

🚧

  • User context keys must have a type of String
  • User context values must have a type of String, Boolean, Number
  • User context keys and values are case sensitive


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 by the Flagship Decision API as targeting criteria for campaign assignment.

The following method from the \Flagship\Visitor instance allows you to set new context values matching the given keys.

use Flagship\Flagship;

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

$visitor->updateContext("lastPurchaseDate", 1615384464);

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

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

Parameter

Type

Description

key

String

Context key.

value

bool or numeric or string

Context value.


  • public function updateContextCollection(array $Context) : void

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

Parameter

Type

Description

context

array (associative array)

collection of keys, values.


  • public function 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, Boolean, Number
  • User context keys and values are case sensitive


Managing visitor campaigns


Synchronizing campaigns

The synchronizeModifications() method of the \Flagship\Visitor instance automatically calls the Flagship Decision API to run campaign assignments according to the current user context and retrieve applicable modifications.

These modifications are then stored in the SDK and updated synchronously when synchronizeModifications() is called.


use Flagship\Flagship;

$visitor = Flagship::newVisitor("your_visitor_id")

$visitor->updateContext("postcode", "31200")

visitor->synchronizeModifications();

  • public function synchronizeModifications() : void

This function will call the decision api and update all the campaigns modifications from the server according to the visitor context.


Getting modifications

Once the campaign has been assigned and synchronized, all the modifications are stored in the SDK. You can retrieve these modifications using the following functions from the \Flagship\Visitor instance:


use Flagship\Flagship;

$visitor = Flagship::newVisitor("your_visitor_id")
$visitor->updateContext("isVip", true)
$visitor->synchronizeModifications();

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

  • public function getModification(string $key, bool|numeric|string|array $defaultValue, bool $activate = false) : bool|numeric|string|array

Retrieve a modification value by its key. If no modification match the given key or if the stored value type and default value type do not match, default value will be returned.

Parameter

Type

Description

key

String

key associated to the modification.

defaultValue

bool or numeric or string or array

default value to return.

activate

bool

(optional) set this parameter to true to automatically report on our server that the current visitor has seen this modification. It is possible to call activateModification() later.


Getting campaign information

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

use Flagship\Flagship;

$visitor = Flagship::newVisitor("your_visitor_id");
$visitor->updateContext("isVip", true);
$visitor->synchronizeModifications();
$info = $visitor->getModificationInfo("displayVipFeature");
  • public function getModificationInfo(string $key) : array|null

Parameter

Type

Description

key

String

Key associated with the modification.

It returns an array containing campaignId, variationGroupId, variationId and isReference keys & values or null if the modification is not found (the user is not affected to the campaign linked to the modification).

Activating modifications

Once a modification is displayed on the screen for a user, you must send an activate event to tell Flagship that the user has seen it.

There are two options for activating a modification:

  1. Pass an activate=true parameter to the getModification() function
  2. Use the following activateModification() method from the visitor instance.

use Flagship\Flagship;

$visitor = Flagship::newVisitor("your_visitor_id");
$visitor->updateContext("isVip", true);
$visitor->synchronizeModifications();

$displayVipFeature = $visitor->getModification("displayVipFeature", false, true); //send an activation event.

    //or

$displayVipFeature = visitor.getModification("displayVipFeature", false);

$visitor.activateModification("displayVipFeature");

  • public function activateModification(string $key) : void

Report this user has seen this modification.

ParameterTypeDescription
keyStringkey associated to the modification to report.


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

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

public function sendHit(HitAbstract $hit) : void

Report this user has seen this modification.

Parameter

Type

Description

hit

HitAbstract

Hit to send.


Page


This hit should be sent each time a visitor arrives on a new page.

use Flagship\Hit\Page;

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

$visitor->sendHit($page);

public Page(string $pageUrl)

Builder Parameter

Type

Description

pageUrl

String

Valid url.

Transaction


This hit should be sent when a user complete a Transaction.

use Flagship\Hit\Transaction;

$transaction = (new Transaction("#12345", "affiliation"))
            ->setCouponCode("code")
            ->setCurrency("EUR")
            ->setItemCount(1)
            ->setPaymentMethod("creditcard")
            ->setShippingCosts(9.99)
            ->setTaxes(19.99)
            ->setTotalRevenue(199.99)
            ->setShippingMethod("1day");

$visitor->sendHit($transaction);

  • public Transaction(string $transactionId, string $affiliation)

Builder Parameter

Type

Description

transactionId

String

Unique identifier for your transaction.

affiliation

String

The name of the KPI that you will have inside your reporting. Learn more

setTotalRevenue

float

(optional) Specifies the total revenue associated with the transaction. This value should include any shipping and/or tax amounts.

setShippingCosts

float

(optional) The total shipping cost of your transaction.

setShippingMethod

String

(optional) The shipping method for your transaction.

setTaxes

float

(optional) Specifies the total amount of taxes in your transaction.

setCurrency

String

(optional) Specifies the currency of your transaction. NOTE: This value should be a valid ISO 4217 currency code.

setPaymentMethod

String

(optional) Specifies the payment method used for your transaction.

setItemCount

int

(optional) Specifies the number of items in your transaction.

setCouponCode

String

(optional) Specifies the coupon code used by the customer in your transaction.


Item


This hit is used to link an item with a transaction. It must be sent after the corresponding transaction hit.

use Flagship\Hit\Item;

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

$visitor->sendHit($item);

  • public Item(string $transactionId, string $productName, string $productSku)
Builder ParameterTypeDescription
transactionIdStringUnique identifier for your transaction.
productNameStringName of your item.
productSkuStringSpecifies the SKU or item code.
setItemCategoryString(optional) Specifies the category that the item belongs to.
setItemPricefloat(optional) Specifies the price for a single item/unit.
setItemQuantityint(optional) Specifies the number of items purchased.

📘

The Item hit isn't available yet in the Flagship reporting view.


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"))
              ->setEventLabel("label")
              ->setEventValue(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
setEventLabelString(optional) Additional description of your event.
setEventValueNumber(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.

Release notes


1.0.0 (Latest version)

  • Release of the PHP SDK with API Mode

Did this page help you?