PHP SDK reference

11 minute readReference

The following information is for the latest SDK version (6.x). The CloudBees platform requires that your installed SDK version be at least 6.x. Please install the latest SDK by following the instructions in the platform UI or in the SDK installation documentation.

Any updates to version 6.x are noted in the platform changelog.

Class Rox

namespace Rox\Server; class Rox

The Rox class provides an interface for the CloudBees platform to manage feature flags that control the behavior of your application. This is the central repository for your application’s flags. This class handles communications with the server to obtain the latest flag values, implement flag settings, and set up flag configurations. It works with a RoxContainer-derived object, which holds your application’s feature flags. The values in the provided container are marked as feature flags and display in the UI once the application is run.

This class also allows you to manage custom properties. These can be static settings of type string, boolean, integer, or double, or you can use a generator class to provide a custom property that is dependent upon code state. These generated properties must derive from CustomPropertyGenerator, which is a template class.

You can also use a RoxOptions object to configure some aspects of this class. You can set the verbosity level, custom platform, global freeze level, impression handler, and fetch handler.

Setup

Configures the Rox object to work with the provided application.

public static function setup($apiKey, RoxOptions $roxOptions = null)
Parameter Modifier and type Description

$apiKey

string

The environment-specific SDK key provided by the platform UI.

$roxOptions

RoxOptions

A RoxOptions instance with the desired configuration for this application.

Shutdown

This method may be used to gracefully shut down the Rox framework, close and clean all consumed resources, and reset the framework’s state.

Use Shutdown only when Rox is set up successfully. Calling Shutdown when it is not possible results in a log warning. You can call Setup again after Shutdown.

In that case, register and setCustomProperty then use a new ROXCore, and register the objects to the UI on the next setup call.

public static function shutdown()

Register

Registers a feature flag container with the Rox client.

The public member variables of this container become a flag in the UI and are named with the object name.

public static function register($namespace, $container) public static function register($container)
Parameter Modifier and type Description

$namespace

string

The optional prefix namespace for all flags in this container (defaults to '').

$container

object

An object that contains your application’s feature flags.

For example, assuming we have the following container:

class MyContainer { public $includeFacebook; public $headline; public function __construct() { $this->includeFacebook = new RoxFlag(); $this->headline = new RoxString("welcome"); } }

And we register the container with the following code:

$flags = new MyContainer(); Rox::register("Login", flags); Rox::setup(rolloutKey);

The flags and configurations in the UI have the names Login.includeFacebook and Login.headline. This can be used to create several namespaces, each with its own group of flags and configurations.

If you do not require a namespace, set it to an empty string. You can also remove a namespace entirely, as it defaults to an empty string.

setCustomComputedBooleanProperty

Sets a computed Boolean custom property on the Rox client. This is a computable Boolean, with an object that generates the value for the property.

public static function setCustomComputedBooleanProperty($name, callable $value)
Parameter Modifier and type Description

$name

string

The name of the property to create.

$value

callable

A function with a context parameter that returns the computed property value.

setCustomComputedDoubleProperty

Sets a computed double custom property on the Rox client. This is a computable double, with an object that generates the value for the property.

public static function setCustomComputedDoubleProperty($name, callable $value)
Parameter Modifier and type Description

$name

string

The name of the property to create.

$value

callable

A function with a context parameter that returns the computed property value.

setCustomComputedIntegerProperty

Sets a computed integer custom property on the Rox client. This is a computable integer, with an object that generates the value for the property.

public static function setCustomComputedIntegerProperty($name, callable $value)
Parameter Modifier and type Description

$name

string

The name of the property to create.

$value

callable

A function with a context parameter that returns the computed property value.

setCustomComputedSemverProperty

Sets a computed semantic-versioned string custom property on the Rox client. This is a computable semantically-versioned string, with an object that generates the value for the property. Refer to the Semantic Versioning documentation for more information.

public static function setCustomComputedSemverProperty($name, callable $value)
Parameter Modifier and type Description

$name

string

The name of the property to create.

$value

callable

A function with a context parameter that returns the computed property value.

setCustomComputedStringProperty

Sets a custom computed string property on the Rox client. This is a computable string, with an object that generates the value for the property.

public static function setCustomComputedStringProperty($name, callable $value)
Parameter Modifier and type Description

$name

string

The name of the property to create.

$value

callable

A function with a context parameter that returns the computed property value.

setCustomBooleanProperty

Sets a custom property representing a Boolean value.

public static function setCustomBooleanProperty($name, $value)
Parameter Modifier and type Description

$name

string

The name of the custom property.

$value

boolean

The value for the custom property, as a Boolean true or false.

setCustomDoubleProperty

Sets a custom property that can store a specified double value.

public static function setCustomDoubleProperty($name, $value)
Parameter Modifier and type Description

$name

string

The name of the custom property.

$value

double

The value of the custom property.

setCustomIntegerProperty

Sets a custom property that can store a specified integer value.

public static function setCustomIntegerProperty($name, $value)
Parameter Modifier and type Description

$name

string

The name of the custom property.

$value

int

The value of the custom property.

setCustomSemverProperty

Sets a custom property that uses a semantic version as its value. Refer to the Semantic Versioning documentation for more information.

public static function setCustomSemverProperty($name, $value)
Parameter Modifier and type Description

$name

string

The name of the custom property.

$value

string

The property value, formatted using the rules defined at https://semver.org/.

setCustomStringProperty

Sets a custom string property for the Rox client, which is a string property you can fetch by name.

public static function setCustomStringProperty($name, $value)
Parameter Modifier and type Description

$name

string

The name of the custom property.

$value

string

The value of the custom property.

setContext

Sets a global context that is available to all flag evaluations.

public static function setContext(ContextInterface $context)

fetch

Creates a network request for the latest configuration.

public static function fetch()

dynamicApi

The returned DynamicApiInterface creates flags as if they were registered, including sending them to the platform UI. This allows you to evaluate flags without having a static container.

Retrieves a dynamic API instance that can be used to get flag values (and create flags) from flag names.

public static function dynamicApi()

setUserspaceUnhandledErrorHandler

A handler for all user function errors, to assist in debugging and to understand unexpected flag values. If this function is not set, errors are logged to the logger.

CloudBees recommends that you wrap all user methods with try-catch to handle errors while in the relevant context, and not after.
public static function setUserspaceUnhandledErrorHandler(callable $userspaceUnhandledErrorHandler)

getState

Use this method to determine the current state of the Rox framework setup.

public static function getState()

The returned integer can be one of the following:

namespace Rox\Server; final class RoxState { const Idle = 0; const SettingUp = 1; const Set = 2; const ShuttingDown = 3; const Corrupted = 4; }

Class RoxOptions

RoxOptions covers configuration options for the Rox client, including logging verbosity. Create instances of this class using RoxOptionsBuilder.

namespace Rox\Server; class RoxOptions implements RoxOptionsInterface

Here is an example of setting up a new RoxOptions object. This object sets the version, the logger, provides an impression handler, and calls the fetch handler.

$options = new RoxOptions(new RoxOptions.RoxOptionsBuilder() ->setVersion("2.0.0") ->setRoxyURL("http://someUrl/") ->setConfigurationFetchedHandler(function (ConfigurationFetchedArgs $args) { //TODO: add things to do when configuration was fetch }, ->setImpressionHandler(function (ImpressionArgs $args) { //TODO: add things to do on impression }, ->setDynamicPropertiesRule(function ($propName, ContextInterface $ctx) { //TODO: return dynamic rule for properties } ->setLogCacheHitsAndMisses(true) ->setCacheStorage(new DoctrineCacheStorage( new ChainCache([ new ArrayCache(), new FilesystemCache('/tmp/rollout/cache'), ]) )) ->setConfigFetchIntervalInSeconds(50) ); Rox::setup(ROLLOUT_KEY, $options);

Class RoxOptionsBuilder

This builder class is used to create a new RoxOptions instance.

namespace Rox\Server; class RoxOptionsBuilder

setVersion

Sets the version of the service running the CloudBees platform SDK.

public function setVersion($version)

setConfigFetchIntervalInSeconds

Sets the HTTP request interval (in seconds) for configuration requests to stay cached and not go to the network.

public function setConfigFetchIntervalInSeconds($configFetchIntervalInSeconds)

setConfigurationFetchedHandler

Sets the configuration event handler. Use this to add actions after configurations are fetched.

public function setConfigurationFetchedHandler($configurationFetchedHandler)

setImpressionHandler

Sets the impression event handler. Use this to add actions after a flag evaluation.

public function setImpressionHandler($impressionHandler)

setDynamicPropertiesRule

$dynamicPropertiesRule is a callable that accepts two parameters.

public function setDynamicPropertiesRule(callable $dynamicPropertiesRule)`
function($propName, ContextInterface $context) {}

The dynamic custom property generator is called when an explicit custom property definition does not exist on the client side.

If you do not set the setDynamicPropertiesRule, it activates the default function, which attempts to extract the property value by calling it by name from the context.

return ($context != null) ? $context->get($propName) : null

setRoxyURL

Sets a roxy URL.

public function setRoxyURL($roxyURL)

setLogCacheHitsAndMisses

Sets a true or false value that indicates whether to log HTTP cache request hits or misses, respectively, to the logger.

public function setLogCacheHitsAndMisses($logCacheHitsAndMisses)

setCacheStorage

Use this cache to keep CloudBees platform configurations local. Defaults to DoctrineCacheStorage, using sys_get_temp_dir().

public function setCacheStorage($cacheStrategy)

setTimeout

Sets a timeout (in seconds, as a float type) on all network requests. The default is no timeout (0).

public function setTimeout($time)

Class RoxFlag

RoxFlag is a Boolean feature flag. It can be either true or false.

namespace Rox\Server\Flags; class RoxFlag implements BooleanFlagInterface

isEnabled

Returns true if the flag is enabled.

function isEnabled($context = null)

getName

The name of the flag.

function getName()

enabled

Executes the provided callable function ($action) if the flag value is true (enabled). If the value is false, it does nothing.

function enabled($context, callable $action)

disabled

Executes the provided callable $action if the flag value is true (disabled). If the value is false, it does nothing.

function disabled($context, callable $action);

Class RoxString

RoxString is a feature flag object that accepts a list of possible string values and a default value. Use this list when selecting new values for the feature, and the value can be overridden via the UI.

namespace Rox\Server\Flags; class RoxString implements StringFlagInterface

Use as in the following example:

$this->titleColorsVariant = new RoxString("Black", ["Red", "Green"]);
if ($container->titleColorsVariant->getValue() == "Black") { // set title color to black } else if ($container->titleColorsVariant->getValue() == "Green") { // set title color to green }

getValue

Returns the flag’s string value considering the given context.

function getValue($context = null)

getName

The name of the flag.

function getName()

Class RoxInt

RoxInt is a feature flag object that accepts a list of possible integer values and a default value. Use this list when selecting new values for the feature, and the value can be overridden via the UI.

namespace Rox\Server\Flags; class RoxInt implements IntFlagInterface

Use as in the following example:

$this->fontSize = new RoxInt(10, [12, 14]);
$fontSize = $container->fontSize->getValue();

getValue

Returns the flag string value, considering the given context.

function getValue($context = null)

getName

The name of the flag.

function getName()

Class RoxDouble

RoxDouble is a feature flag object that accepts a list of possible double values and a default value. Use this list when selecting new values for the feature, and the value can be overridden via the UI.

namespace Rox\Server\Flags; class RoxDouble implements DoubleFlagInterface

Use as in the following example:

$this->someDouble = new RoxDouble(1.1, [2.2, 3.3]);
$doubleValue = $container->someDouble->getValue();

getValue

Returns the flag string value considering the given context.

function getValue($context = null)

getName

The name of the flag.

function getName()

Interface ContextInterface

The context object passes data to the flag when checking whether the current flag is enabled or disabled. This object is used by the registered custom properties to evaluate the flag configuration and return the flag value.

Create a context using the ContextBuilder and send a key/value map to its build function.

namespace Rox\Core\Context; interface ContextInterface

Use as in the following example:

use Rox\Core\Context\ContextBuilder; $context = (new ContextBuilder())->build([ "user" => $currentUser ]);

get

This get function is used to retrieve data from the context.

function get($key);

In the following example, the setCustomComputedStringProperty uses the context to get the username.

use Rox\Core\Context\ContextInterface; Rox::setCustomComputedStringProperty("user_name", function (ContextInterface $context) { return $context->get("user")->getName(); });

Class UserspaceUnhandledErrorArgs

Use as follows:

namespace Rox\Core\ErrorHandling; final class UserspaceUnhandledErrorArgs

getExceptionSource

Returns the user-defined source object that caused the exception. For the impression invoker handler or configuration fetched handler, the returned object is a handler function. For dynamic property and custom property rules, it is the rule function.

getExceptionTrigger

Returns integer code from the following list:

namespace Rox\Core\ErrorHandling; final class ExceptionTrigger { const DynamicPropertiesRule = 1; const ConfigurationFetchedHandler = 2; const ImpressionHandler = 3; const CustomPropertyGenerator = 4; }

getException

Returns the exception itself.

Use as in the following example:

$dynamicPropertiesRule = function ($propName, ContextInterface $context) { // write some custom logic return $context->get($propName); }; $roxOptionsBuilder->setDynamicPropertiesRule($dynamicPropertiesRule); Rox::setUserspaceUnhandledErrorHandler(function (UserspaceUnhandledErrorArgs $args) use ($dynamicPropertiesRule) { if ($args->getExceptionSource() === $dynamicPropertiesRule) { // add some action } });

Using ConfigurationFetchedHandler

As described in RoxOptions, use setConfigurationFetchedHandler to set the configuration fetched event handler function.

Use as follows:

function (ConfigurationFetchedArgs $args) { // function code... }

Below are additional definitions for use.

ConfigurationFetchedArgs

Use as follows:

namespace Rox\Core\Configuration; class ConfigurationFetchedArgs

getCreationDate

Reads the configuration creation date, if fetched successfully.

isHasChanges

Checks whether the last fetch contained any changes in the configuration.

getErrorDetails

Returns an integer code which can be one of the described below.

FetcherError

Numeric fetch error code.

namespace Rox\Core\Configuration; final class FetcherError { const NoError = 0; const CorruptedJson = 1; const EmptyJson = 2; const SignatureVerificationError = 3; const NetworkError = 4; const MismatchAppKey = 5; const Unknown = 6; }

getFetcherStatus

Returns the numeric code of the configuration fetch status.

public function getFetcherStatus()

Can be one of the following:

FetcherStatus

Use as follows:

namespace Rox\Core\Configuration; final class FetcherStatus { const AppliedFromEmbedded = 1; const AppliedFromLocalStorage = 2; const AppliedFromNetwork = 3; const ErrorFetchedFailed = 4; }

Using ImpressionHandler

The impressionHandler function that you can provide to RoxOptions helps determine what actions should be taken after a flag evaluation.

The function signature:

function (ImpressionArgs $args)

Class ImpressionArgs

Use as follows:

namespace Rox\Core\Impression; class ImpressionArgs

getReportingValue

The returned object has three properties: the flag name, the value, and targeting (whether the flag has configuration status on or off).

function getReportingValue()
Property Description
function getName()

The flag name.

function getValue()

The evaluation result.

function isTargeting()

Whether targeting is on or off.

getContext

Returns the context in which the impression is called. This is a merged context containing the global context and the call’s context.

public function getContext()

Interface DynamicApiInterface

An alternative to using a container with the Rox::register method. This allows you to evaluate flags without having a static container. The dynamic API creates flags as if they were registered, including sending them to the UI.

namespace Rox\Core\Client; interface DynamicApiInterface

isEnabled

Evaluate a Boolean flag.

function isEnabled($name, $defaultValue, ContextInterface $context = null);
Parameter Modifier and type Description

$name

string

The flag name (including an optional namespace). Throws an error if null.

$defaultValue

bool

The default value to use if there are no UI configurations.

$context

ContextInterface

A context for evaluating the flag that is merged with the global context.

getValue

Evaluate a string flag.

function getValue($name, $defaultValue, $variations = [], ContextInterface $context = null);
Parameter Modifier and type Description

$name

string

The flag name (including an optional namespace). Throws an error if null.

$defaultValue

string

The default value to use if there are no UI configurations.

$variations

array

All alternative values. Can be used and updated in the UI. Must not contain any null values.

$context

ContextInterface

A context for evaluating the flag that is merged with the global context.

getInt

Evaluate an integer flag.

function getInt($name, $defaultValue, $variations = [], ContextInterface $context = null);
Parameter Modifier and type Description

$name

string

The flag name (including an optional namespace). Throws an error if null.

$defaultValue

int

The default value to use if there are no UI configurations.

$variations

array

All alternative values. Can be used and updated in the UI. Cannot contain nulls.

$context

ContextInterface

A context for evaluating the flag that is merged with the global context.

getDouble

Evaluate a double flag.

function getDouble($name, $defaultValue, $variations = [], ContextInterface $context = null);
Parameter Modifier and type Description

$name

string

The flag name (including an optional namespace). Throws an error if null.

$defaultValue

double

The default value to use if there are no UI configurations.

$variations

array

All alternative values. Can be used and updated in the UI. Cannot contain nulls.

$context

ContextInterface

A context for evaluating the flag that is merged with the global context.