Skip to main content
Version: Config V2

PHP SDK Reference

Star on GitHub Build Status Latest Stable Version Total Downloads Sonar Quality Gate Sonar Coverage

ConfigCat PHP SDK on GitHub

Getting started

1. Install the package with Composer

composer require configcat/configcat-client

2. Create the ConfigCat client with your SDK Key

$client = new \ConfigCat\ConfigCatClient("#YOUR-SDK-KEY#");

3. Get your setting value

$isMyAwesomeFeatureEnabled = $client->getValue("isMyAwesomeFeatureEnabled", false);
if (is_bool($isMyAwesomeFeatureEnabled) && $isMyAwesomeFeatureEnabled) {
doTheNewThing();
} else {
doTheOldThing();
}

Creating the ConfigCat Client

ConfigCat Client is responsible for:

  • managing the communication between your application and ConfigCat servers.
  • caching your setting values and feature flags.
  • serving values quickly in a failsafe way.

Constructor parameters:

NameTypeDescription
sdkKeystringREQUIRED. SDK Key to access your feature flag and setting. Get it from ConfigCat Dashboard.
optionsarrayOptional. Additional SDK options, see below for the detailed list.

Available options:

NameTypeDescription
data-governanceintOptional, defaults to DataGovernance::GLOBAL_. Describes the location of your feature flag and setting data within the ConfigCat CDN. This parameter needs to be in sync with your Data Governance preferences. More about Data Governance. Available options: GLOBAL_, EU_ONLY.
logger\Psr\Log\LoggerInterfaceOptional, sets the logger for errors and warnings produced by the SDK, defaults to Monolog. More about logging.
log-levelintOptional, defaults to LogLevel::WARNING. Sets the internal log level. More about log levels.
cache\ConfigCat\Cache\ConfigCacheOptional, sets a \ConfigCat\Cache\ConfigCache implementation for caching the latest feature flag and setting values. More about cache. You can check the currently available implementations here.
cache-refresh-intervalintOptional, sets the refresh interval of the cache in seconds, after the initial cached value is set this value will be used to determine how much time must pass before initiating a config JSON download. Defaults to 60.
request-optionsarray(Deprecated) Optional, sets the request options (e.g. HTTP Timeout, HTTP Proxy) for the underlying Guzzle HTTP client used for downloading the config JSON files. See Guzzle's official documentation for the available request options.
fetch-client\ConfigCat\Http\FetchClientInterfaceCustom fetch client that wraps an actual HTTP client used to make HTTP requests towards ConfigCat. When it's not set, \ConfigCat\Http\GuzzleFetchClient is used by default.
flag-overrides\ConfigCat\Override\FlagOverridesOptional, sets the local feature flag & setting overrides. More about feature flag overrides.
exceptions-to-ignorearrayOptional, sets an array of exception classes that should be ignored from logs.
base-urlstringOptional, sets the CDN base url (forward proxy, dedicated subscription) from where the SDK will download the feature flags and settings.
default-user\ConfigCat\UserOptional, sets the default user. More about default user.
offlineboolOptional, defaults to false. Indicates whether the SDK should be initialized in offline mode. More about offline mode.
info

Each option name is available through constants of the \ConfigCat\ClientOptions class.

Example:

$client = new \ConfigCat\ConfigCatClient("#YOUR-SDK-KEY#", [
\ConfigCat\ClientOptions::CACHE => new \ConfigCat\Cache\LaravelCache(Cache::store()),
\ConfigCat\ClientOptions::CACHE_REFRESH_INTERVAL => 5
]);

Anatomy of getValue()

ParametersDescription
keyREQUIRED. Setting-specific key. Set on ConfigCat Dashboard for each setting.
defaultValueREQUIRED. This value will be returned in case of an error.
userOptional, User Object. Essential when using Targeting. Read more about Targeting.
$value = $client->getValue(
"keyOfMySetting", # Setting Key
false, # Default value
new \ConfigCat\User('#UNIQUE-USER-IDENTIFIER#') # Optional User Object
);

Anatomy of getValueDetails()

getValueDetails() is similar to getValue() but instead of returning the evaluated value only, it gives more detailed information about the evaluation result.

ParametersDescription
keyREQUIRED. The key of a specific setting or feature flag. Set on ConfigCat Dashboard for each setting.
defaultValueREQUIRED. This value will be returned in case of an error.
userOptional, User Object. Essential when using Targeting. Read more about Targeting.
$details = $client->getValueDetails(
"keyOfMySetting", # Setting Key
false, # Default value
new \ConfigCat\User('#UNIQUE-USER-IDENTIFIER#') # Optional User Object
);

The details result contains the following information:

PropertyTypeDescription
getKey()stringThe key of the evaluated feature flag or setting.
getValue()bool / string / int / doubleThe evaluated value of the feature flag or setting.
getUser()?\ConfigCat\UserThe User Object used for the evaluation.
isDefaultValue()boolTrue when the default value passed to getValueDetails() is returned due to an error.
getErrorMessage()?stringIn case of an error, this property contains the error message.
getErrorException()?ThrowableIn case of an error, this property contains the related exception object (if any).
getMatchedTargetingRule()?arrayThe Targeting Rule (if any) that matched during the evaluation and was used to return the evaluated value.
getMatchedPercentageOption()?arrayThe Percentage Option (if any) that was used to select the evaluated value.
getFetchTimeUnixMilliseconds()floatThe last download time of the current config in unix milliseconds format.

User Object

The User Object is essential if you'd like to use ConfigCat's Targeting feature.

$user = new \ConfigCat\User("#UNIQUE-USER-IDENTIFIER#");
$user = new \ConfigCat\User("[email protected]");

Customized User Object creation

ParametersDescription
identifierREQUIRED. Unique identifier of a user in your application. Can be any string value, even an email address.
emailOptional parameter for easier Targeting Rule definitions.
countryOptional parameter for easier Targeting Rule definitions.
customOptional associative array representing the custom attributes of a user for advanced Targeting Rule definitions. e.g. User role, Subscription type. The value's type of the array must be a string, int, float, DateTimeInterface or an array of string.
$user = new \ConfigCat\User(
'#UNIQUE-USER-IDENTIFIER#',
'john@example',
'United Kingdom',
[
'SubscriptionType' => 'Pro',
'UserRole' => 'Admin'
]);
caution

If you want to use a string value containing non-ASCII characters as a user attribute, please make sure that the content of the string is a UTF-8 byte sequence. (A PHP string is just a sequence of bytes, it doesn't use any internal character encoding, that is, doesn't offer native Unicode support. Thus, to support Unicode text, the ConfigCat SDK assumes UTF-8 encoding.)

The custom array also allows attribute values other than string values:

$user = new \ConfigCat\User(
'#UNIQUE-USER-IDENTIFIER#',
null,
null,
[
'Rating' => 4.5,
'RegisteredAt' => new DateTimeImmutable('2023-11-22T12:34:56.0000000Z'),
'Roles' => ['Role1', 'Role2']
]);

User Object Attribute Types

All comparators support string values as User Object attribute (in some cases they need to be provided in a specific format though, see below), but some of them also support other types of values. It depends on the comparator how the values will be handled. The following rules apply:

Text-based comparators (EQUALS, IS ONE OF, etc.)

  • accept string values,
  • all other values are automatically converted to string (a warning will be logged but evaluation will continue as normal).

SemVer-based comparators (IS ONE OF, <, >=, etc.)

  • accept string values containing a properly formatted, valid semver value,
  • all other values are considered invalid (a warning will be logged and the currently evaluated Targeting Rule will be skipped).

Number-based comparators (=, <, >=, etc.)

  • accept int or float values,
  • accept string values containing a properly formatted, valid int or float value,
  • all other values are considered invalid (a warning will be logged and the currently evaluated Targeting Rule will be skipped).

Date time-based comparators (BEFORE / AFTER)

  • accept DateTimeInterface values, which are automatically converted to a second-based Unix timestamp,
  • accept int or float values representing a second-based Unix timestamp,
  • accept string values containing a properly formatted, valid int or float value,
  • all other values are considered invalid (a warning will be logged and the currently evaluated Targeting Rule will be skipped).

String array-based comparators (ARRAY CONTAINS ANY OF / ARRAY NOT CONTAINS ANY OF)

  • accept arrays of string,
  • accept string values containing a valid JSON string which can be deserialized to an array of string,
  • all other values are considered invalid (a warning will be logged and the currently evaluated Targeting Rule will be skipped).

Default user

There's an option to set a default User Object that will be used at feature flag and setting evaluation. It can be useful when your application has a single user only, or rarely switches users.

You can set the default User Object either on SDK initialization:

$client = new \ConfigCat\ConfigCatClient("#YOUR-SDK-KEY#", [
\ConfigCat\ClientOptions::DEFAULT_USER => new \ConfigCat\User("[email protected]"),
]);

or with the setDefaultUser() method of the ConfigCat client.

$client->setDefaultUser(new \ConfigCat\User("[email protected]"));

Whenever the getValue(), getValueDetails(), getAllValues(), or getAllVariationIds() methods are called without an explicit user parameter, the SDK will automatically use the default user as a User Object.

$user = new \ConfigCat\User("[email protected]");
$client->setDefaultUser($user);

// The default user will be used at the evaluation process.
$value = $client->getValue("keyOfMySetting", false);

When the user parameter is specified on the requesting method, it takes precedence over the default user.

$user = new \ConfigCat\User("[email protected]");
$client->setDefaultUser($user);

$otherUser = new \ConfigCat\User("[email protected]");

// $otherUser will be used at the evaluation process.
$value = $client->getValue("keyOfMySetting", false, $otherUser);

For deleting the default user, you can do the following:

$client->clearDefaultUser();

getAllKeys()

You can query the keys of each feature flag and setting with the getAllKeys() method.

$client = new \ConfigCat\ConfigCatClient("#YOUR-SDK-KEY#");
$keys = $client->getAllKeys();

getAllValues()

Evaluates and returns the values of all feature flags and settings. Passing a User Object is optional.

$client = new \ConfigCat\ConfigCatClient("#YOUR-SDK-KEY#");
$settingValues = $client->getAllValues();

// invoke with User Object
$user = new \ConfigCat\User("[email protected]");
$settingValuesTargeting = $client->getAllValues($user);

Hooks

With the following hooks you can subscribe to particular events fired by the SDK:

  • onConfigChanged([key => setting]): This event is sent when the SDK loads a valid config JSON into memory from cache, and each subsequent time when the loaded config JSON changes via HTTP.

  • onFlagEvaluated(EvaluationDetails): This event is sent each time when the SDK evaluates a feature flag or setting. The event sends the same evaluation details that you would get from getValueDetails().

  • onError(string): This event is sent when an error occurs within the ConfigCat SDK.

You can subscribe to these events with the hooks property of the ConfigCat client:

$client->hooks()->addOnFlagEvaluated(function (EvaluationDetails $details) {
/* handle the event */
});

Online / Offline mode

In cases when you'd want to prevent the SDK from making HTTP calls, you can put it in offline mode:

$client->setOffline();

In offline mode, the SDK won't initiate HTTP requests and will work only from its cache.

To put the SDK back in online mode, you can do the following:

$client->setOnline();

With $client->isOffline() you can check whether the SDK is in offline mode.

Flag Overrides

With flag overrides you can overwrite the feature flags & settings downloaded from the ConfigCat CDN with local values. Moreover, you can specify how the overrides should apply over the downloaded values. The following 3 behaviours are supported:

  • Local only (OverrideBehaviour::LOCAL_ONLY): When evaluating values, the SDK will not use feature flags & settings from the ConfigCat CDN, but it will use all feature flags & settings that are loaded from local-override sources.

  • Local over remote (OverrideBehaviour::LOCAL_OVER_REMOTE): When evaluating values, the SDK will use all feature flags & settings that are downloaded from the ConfigCat CDN, plus all feature flags & settings that are loaded from local-override sources. If a feature flag or a setting is defined both in the downloaded and the local-override source then the local-override version will take precedence.

  • Remote over local (OverrideBehaviour::REMOTE_OVER_LOCAL): When evaluating values, the SDK will use all feature flags & settings that are downloaded from the ConfigCat CDN, plus all feature flags & settings that are loaded from local-override sources. If a feature flag or a setting is defined both in the downloaded and the local-override source then the downloaded version will take precedence.

You can load your feature flag & setting overrides from a file or from a simple associative array.

JSON File

The SDK can be set up to load your feature flag & setting overrides from a file. You can also specify whether the file should be reloaded when it gets modified.

$client = new \ConfigCat\ConfigCatClient("localhost", [
\ConfigCat\ClientOptions::FLAG_OVERRIDES => new \ConfigCat\Override\FlagOverrides(
\ConfigCat\Override\OverrideDataSource::localFile("path/to/the/local_flags.json"), // path to the file
\ConfigCat\Override\OverrideBehaviour::LOCAL_ONLY
),
]);

JSON File Structure

The SDK supports 2 types of JSON structures to describe feature flags & settings.

1. Simple (key-value) structure
{
"flags": {
"enabledFeature": true,
"disabledFeature": false,
"intSetting": 5,
"doubleSetting": 3.14,
"stringSetting": "test"
}
}

This is the same format that the SDK downloads from the ConfigCat CDN. It allows the usage of all features that are available on the ConfigCat Dashboard.

You can download your current config JSON from ConfigCat's CDN and use it as a baseline.

The URL to your current config JSON is based on your Data Governance settings:

  • GLOBAL: https://cdn-global.configcat.com/configuration-files/{YOUR-SDK-KEY}/config_v6.json
  • EU: https://cdn-eu.configcat.com/configuration-files/{YOUR-SDK-KEY}/config_v6.json
{
"f": {
// list of feature flags & settings
"isFeatureEnabled": {
// key of a particular flag
"v": false, // default value, served when no rules are defined
"i": "430bded3", // variation id (for analytical purposes)
"t": 0, // feature flag's type, possible values:
// 0 -> BOOLEAN
// 1 -> STRING
// 2 -> INT
// 3 -> DOUBLE
"p": [
// list of percentage rules
{
"o": 0, // rule's order
"v": true, // value served when the rule is selected during evaluation
"p": 10, // % value
"i": "bcfb84a7" // variation id (for analytical purposes)
},
{
"o": 1, // rule's order
"v": false, // value served when the rule is selected during evaluation
"p": 90, // % value
"i": "bddac6ae" // variation id (for analytical purposes)
}
],
"r": [
// list of Targeting Rules
{
"o": 0, // rule's order
"a": "Identifier", // comparison attribute
"t": 2, // comparator, possible values:
// 0 -> 'IS ONE OF',
// 1 -> 'IS NOT ONE OF',
// 2 -> 'CONTAINS',
// 3 -> 'DOES NOT CONTAIN',
// 4 -> 'IS ONE OF (SemVer)',
// 5 -> 'IS NOT ONE OF (SemVer)',
// 6 -> '< (SemVer)',
// 7 -> '<= (SemVer)',
// 8 -> '> (SemVer)',
// 9 -> '>= (SemVer)',
// 10 -> '= (Number)',
// 11 -> '<> (Number)',
// 12 -> '< (Number)',
// 13 -> '<= (Number)',
// 14 -> '> (Number)',
// 15 -> '>= (Number)',
// 16 -> 'IS ONE OF (Hashed)',
// 17 -> 'IS NOT ONE OF Hashed)'
"c": "@example.com", // comparison value
"v": true, // value served when the rule is selected during evaluation
"i": "bcfb84a7" // variation id (for analytical purposes)
}
]
}
}
}

Associative Array

You can set up the SDK to load your feature flag & setting overrides from an associative array.

$client = new \ConfigCat\ConfigCatClient("localhost", [
\ConfigCat\ClientOptions::FLAG_OVERRIDES => new \ConfigCat\Override\FlagOverrides(
\ConfigCat\Override\OverrideDataSource::localArray([
'enabledFeature' => true,
'disabledFeature' => false,
'intSetting' => 5,
'doubleSetting' => 3.14,
'stringSetting' => "test",
]), \ConfigCat\Override\OverrideBehaviour::LOCAL_ONLY),
]);

Cache

You can use the following caching options:

  • Laravel:

    $client = new \ConfigCat\ConfigCatClient("#YOUR-SDK-KEY#", [
    \ConfigCat\ClientOptions::CACHE => new \ConfigCat\Cache\LaravelCache(\Illuminate\Support\Facades\Cache::store()),
    ]);
  • PSR-6 cache (e.g. the redis adapter for PSR-6):

    $client = new \RedisArray(['127.0.0.1:6379', '127.0.0.2:6379']);
    $pool = new RedisCachePool($client);

    $client = new \ConfigCat\ConfigCatClient("#YOUR-SDK-KEY#", [
    \ConfigCat\ClientOptions::CACHE => new \ConfigCat\Cache\Psr6Cache($pool),
    ]);

    or with the file system adapter:

    $filesystemAdapter = new \League\Flysystem\Adapter\Local(__DIR__.'/');
    $filesystem = new \League\Flysystem\Filesystem($filesystemAdapter);
    $pool = new \Cache\Adapter\Filesystem\FilesystemCachePool($filesystem);

    $client = new \ConfigCat\ConfigCatClient("#YOUR-SDK-KEY#", [
    \ConfigCat\ClientOptions::CACHE => new \ConfigCat\Cache\Psr6Cache($pool),
    ]);
  • PSR-16 cache (e.g. the redis adapter for PSR-6 and the PSR-6 to PSR-16 cache bridge):

    $client = new \RedisArray(['127.0.0.1:6379', '127.0.0.2:6379']);
    $pool = new RedisCachePool($client);
    $simpleCache = new SimpleCacheBridge($pool);

    $client = new \ConfigCat\ConfigCatClient("#YOUR-SDK-KEY#", [
    \ConfigCat\ClientOptions::CACHE => new \ConfigCat\Cache\Psr16Cache($simpleCache),
    ]);

    or with the file system adapter:

    $filesystemAdapter = new \League\Flysystem\Adapter\Local(__DIR__.'/');
    $filesystem = new \League\Flysystem\Filesystem($filesystemAdapter);
    $pool = new \Cache\Adapter\Filesystem\FilesystemCachePool($filesystem);
    $simpleCache = new SimpleCacheBridge($pool);

    $client = new \ConfigCat\ConfigCatClient("#YOUR-SDK-KEY#", [
    \ConfigCat\ClientOptions::CACHE => new \ConfigCat\Cache\Psr16Cache($simpleCache),
    ]);
  • Custom cache implementation

    class CustomCache extends \ConfigCat\Cache\ConfigCache
    {
    protected function get(string $key): ?string
    {
    // load from cache
    }

    protected function set(string $key, string $value): void
    {
    // save into cache
    }
    }
info

The PHP SDK supports shared caching. You can read more about this feature and the required minimum SDK versions here.

Logging

The SDK uses the PSR-3 LoggerInterface for logging, so you can use any implementor package like Monolog.

$client = new \ConfigCat\ConfigCatClient("#YOUR-SDK-KEY#", [
\ConfigCat\ClientOptions::LOGGER => new \Monolog\Logger("name"),
]);

You can change the verbosity of the logs by setting the log-level option.

$client = new \ConfigCat\ConfigCatClient("#YOUR-SDK-KEY#", [
\ConfigCat\ClientOptions::LOG_LEVEL => \ConfigCat\Log\LogLevel::INFO
]);

The following levels are used by the ConfigCat SDK:

LevelDescription
NO_LOGTurn the logging off.
ERROROnly error level events are logged.
WARNINGDefault. Errors and Warnings are logged.
INFOErrors, Warnings and feature flag evaluation is logged.
DEBUGAll of the above plus debug info is logged. Debug logs can be different for other SDKs.

Info level logging helps to inspect how a feature flag was evaluated:

[2022-01-06T18:34:16.846039+00:00] ConfigCat.INFO: [5000] Evaluating 'isPOCFeatureEnabled' for User '{"Identifier":"<SOME USERID>","Email":"[email protected]","Country":"US","SubscriptionType":"Pro","Role":"Admin","version":"1.0.0"}'
Evaluating targeting rules and applying the first match if any:
- IF User.Email CONTAINS ANY OF ['@something.com'] THEN 'false' => no match
- IF User.Email CONTAINS ANY OF ['@example.com'] THEN 'true' => MATCH, applying rule
Returning 'true'.

HTTP Client

The SDK by default uses Guzzle for the underlying HTTP calls. The default HTTP client is customizable through the \ConfigCat\Http\GuzzleFetchClient::create() method at the SDK's initialization. To learn more about Guzzle's customization options see the official documentaion.

$client = new \ConfigCat\ConfigCatClient("#YOUR-SDK-KEY#", [
\ConfigCat\ClientOptions::FETCH_CLIENT => \ConfigCat\Http\GuzzleFetchClient::create([
\GuzzleHttp\RequestOptions::CONNECT_TIMEOUT => 5,
]),
]);

Through the \ConfigCat\ClientOptions::FETCH_CLIENT option you can pass your own HTTP client by providing a \ConfigCat\Http\FetchClientInterface implementation.

class CustomFetchClient implements \ConfigCat\Http\FetchClientInterface
{
public function getClient(): \Psr\Http\Client\ClientInterface
{
// return with a \Psr\Http\Client\ClientInterface implementation.
}

public function createRequest(string $method, string $uri): \Psr\Http\Message\RequestInterface
{
// return with a \Psr\Http\Message\RequestInterface implementation
}
}
$client = new \ConfigCat\ConfigCatClient("#YOUR-SDK-KEY#", [
\ConfigCat\ClientOptions::FETCH_CLIENT => new CustomFetchClient(),
]);

HTTP Proxy

If your application runs behind a proxy you can do the following:

$client = new \ConfigCat\ConfigCatClient("#YOUR-SDK-KEY#", [
\ConfigCat\ClientOptions::REQUEST_OPTIONS => [
\GuzzleHttp\RequestOptions::PROXY => [
'http' => 'tcp://localhost:8125',
'https' => 'tcp://localhost:9124',
]
],
]);

HTTP Timeout

You can set the maximum wait time for a ConfigCat HTTP response by using Guzzle's timeouts.

$client = new \ConfigCat\ConfigCatClient("#YOUR-SDK-KEY#", [
\ConfigCat\ClientOptions::REQUEST_OPTIONS => [
\GuzzleHttp\RequestOptions::CONNECT_TIMEOUT => 5,
\GuzzleHttp\RequestOptions::TIMEOUT => 10
],
]);

Sample Applications

Guides

See this guide on how to use ConfigCat's PHP SDK.

Look under the hood