The Unleash PHP SDK lets you evaluate feature flags in PHP applications. It connects to Unleash or Unleash Edge to fetch flag configurations and evaluates them locally against an Unleash context.
You can use this SDK with Unleash Enterprise or Unleash Open Source.
For an overview of how Unleash SDKs work, including offline behavior, feature compatibility across SDKs, and default refresh and metrics intervals, refer to the SDK overview.
For event support, you also need symfony/event-dispatcher. See the event documentation.
or
The basic usage is getting the Unleash object and checking for a feature:
You can (and in some cases you must) also provide a context object. If the feature doesn’t exist on the server
you will get false from isEnabled(), but you can change the default value to true.
The builder contains many configuration options, and it’s advised to always use the builder to construct an Unleash instance. The builder is immutable.
The builder object can be created using the create() static method or by using its constructor:
You can replace various parts of the Unleash SDK with custom implementation using the builder, like custom registration service, custom metrics handler and so on.
Replaceable parts (some of them have further documentation below):
withRegistrationService())withContextProvider())withBootstrapHandler())withEventDispatcher())withMetricsHandler())withVariantHandler())Dependencies can be injected by implementing one of the following interfaces from the Unleash\Client\Helper\Builder namespace:
CacheAware - injects standard cacheConfigurationAware - injects the global configuration objectHttpClientAware - injects the http clientMetricsSenderAware - injects the metrics sender serviceRequestFactoryAware - injects the request factoryStaleCacheAware - injects the stale cache handlerStickinessCalculatorAware - injects the stickiness calculator used for calculating stickiness in gradual rollout strategyIn addition to the parts above these interfaces can also be implemented by these kinds of classes:
Some classes cannot depend on certain objects, namely any object that is present in the configuration cannot implement ConfigurationAware (to avoid circular dependency). The same classes also cannot implement MetricsSenderAware because metrics sender depends on the configuration object. You will get a \Unleash\Client\Exception\CyclicDependencyException if that happens.
Example:
The app name, instance id and app url are required as per the specification.
If you’re using Unleash v4 you also need to specify authorization key (API key), you can do so with custom header.
To filter feature flags by tag or name prefix you can use the Url helper:
Some optional parameters can be set, these include:
The builder will attempt to load http client and request factory implementations automatically. Most implementations, such as guzzlehttp/guzzle or symfony/http-client (in combination with nyholm/psr7), will be loaded automatically. If the builder is unable to locate a http client or request factory implementation, you will need to provide some implementation on your own.
If you use symfony/cache or cache/filesystem-adapter as your cache implementation, the cache handler will be created automatically, otherwise you need to provide some implementation on your own.
For some use cases the builder can return intermediate objects, for example the UnleashRepository object. This can be
useful if you need to directly interact with the repository, to refresh the cache manually for example.
By default the SDK uses the backend endpoints on the Unleash API. You can also use Frontend API mode, which is a lightweight mode that uses the Frontend API endpoints. Frontend API mode provides a substantial performance improvement when using a large set of feature flags (10K+).
To use Frontend API mode, call withProxy($apiKey) on the builder. The $apiKey needs to be a frontend token. Note that withProxy($apiKey) sets the API key directly, so you don’t need to set the API key header separately.
Example of using the builder to create a Frontend API mode instance:
As of version 1.12, Frontend API mode requires Edge, so the appUrl needs to point to the Edge server.
Not supported in Frontend API mode:
It would be slow to perform a http request every time you check if a feature is enabled, especially in popular apps. That’s why this library has built-in support for PSR-16 cache implementations.
If you don’t provide any implementation and default implementation exists, it’s used, otherwise you’ll get an exception. You can also provide a TTL which defaults to 15 seconds for standard cache and 30 minutes for stale data cache.
Stale data cache is used when http communication fails while fetching feature list from the server. In that case the latest valid version is used until the TTL expires or server starts responding again. An event gets emitted when this happens, for more information see events documentation.
Cache implementations supported out of the box (meaning you don’t need to configure anything):
You can use a different cache implementation for standard item cache and for stale cache. If you don’t provide any implementation for stale cache, the same instance as for standard cache is used.
You can set a default response from the SDK in cases when for some reason contacting Unleash server fails.
By default, you can bootstrap using:
SplFileInfo)arrayTraversableJsonSerializableThese correspond to bootstrap providers:
JsonBootstrapProvider (json string)FileBootstrapProvider (file, URL address, custom stream wrapper path)JsonSerializableBootstrapProvider (array, Traversable, JsonSerializable)EmptyBootstrapProvider (default provider that doesn’t provide any bootstrap)CompoundBootstrapProvider (can contain multiple bootstrap providers and tries them one by one)Examples of bootstraps:
Using bootstrap providers directly:
Using multiple bootstrap providers:
Creating a custom bootstrap provider is very simple, just implement the BootstrapProvider interface and use your
class in the builder:
It may be useful to disable communication with the Unleash server for local development and using a bootstrap instead.
Note that when you disable communication with Unleash and don’t provide a bootstrap, an exception will be thrown.
Set the cache interval to 0 to always have a fresh bootstrap content.
The usually required parameters (app name, instance id, app url) are not required when communication is disabled.
Unleash servers can use multiple strategies for enabling or disabling features. Which strategy gets used is defined on the server. This implementation supports all v4 strategies. More here.
This is the simplest of them and simply always returns true if the feature defines default as its chosen strategy and doesn’t need any context parameters.
Enables feature based on the IP address. Takes current user’s IP address from the context object. You can provide your
own IP address or use the default ($_SERVER['REMOTE_ADDR']). Providing your own is especially useful if you’re behind
proxy and thus REMOTE_ADDR would return your proxy server’s IP address instead.
As of 1.4.0 the CIDR notation is supported
Enables feature based on the user ID. The user ID can be any string. You must always provide your own user id via context.
Also known as flexible rollout. Allows you to enable feature for only a percentage of users based on their user id, session id or randomly. The default is to try in this order: user id, session id, random.
If you specify the user id type on your Unleash server, you must also provide the user id via context, same as in the
User ID strategy. Session ID can also be provided via context, it defaults to the current session id via session_id()
call.
This strategy requires a stickiness calculator that transforms the id (user, session or random) into a number between 1 and 100. You can provide your own or use the default \Unleash\Client\Stickiness\MurmurHashCalculator
This strategy allows you to match against a list of server hostnames (which are not the same as http hostnames).
If you don’t specify a hostname in context, it defaults to the current hostname using
gethostname().
This library also implements some deprecated strategies, namely gradualRolloutRandom, gradualRolloutSessionId
and gradualRolloutUserId which all alias to the Gradual rollout strategy.
Manually creating relevant context can get tiring real fast. Luckily you can create your own context provider that will do it for you!
To implement your own strategy you need to create a class implementing StrategyHandler (or AbstractStrategyHandler
which contains some useful methods). Then you need to instruct the builder to use your custom strategy.
Now you must instruct the builder to use your new strategy
You can use multiple variants of one feature, for example for A/B testing. If no variant matches or the feature doesn’t
have any variants, a default one will be returned which returns false for isEnabled(). You can also provide your
own default variant.
Variant may or may not contain a payload.
By default, the library automatically registers itself as an application in the Unleash server. If you want to prevent
this, use withAutomaticRegistrationEnabled(false) in the builder.
By default, this library sends metrics which are simple statistics about whether user was granted access or not.
The metrics will be bundled and sent once the bundle created time crosses the configured threshold. By default this threshold is 30,000 milliseconds (30 seconds) meaning that when a new bundle gets created it won’t be sent sooner than in 30 seconds. That doesn’t mean it’s guaranteed that the metrics will be sent every 30 seconds, it only guarantees that the metrics won’t be sent sooner.
Example:
In the example above the metric bundle gets sent after 1 minute and 5 seconds because there was no one to trigger the code.
While middlewares for http client are not natively supported by this SDK, you can pass your own http client which supports them.
The most popular http client, guzzle, supports them out of the box and here’s an example of how to pass custom headers automatically (for more information visit official guzzle documentation on middlewares):
Constraints are supported by this SDK and will be handled correctly by Unleash::isEnabled() if present.
withGitlabEnvironment() method in builder, it’s an alias to withAppName() but
communicates the intent better.Check out our guide for more information on how to build and scale feature flag systems.
If you’re using Symfony, the Unleash Symfony Bundle provides framework-level integration with automatic dependency injection and configuration.
If you’re upgrading from v1, read the v2 migration guide.