rikudou / unleash-sdk
Requires
- php: ^8.0
- ext-json: *
- lastguest/murmurhash: ^2.1
- psr/http-client: ^1.0
- psr/http-client-implementation: ^1.0
- psr/http-factory: ^1.0
- psr/http-factory-implementation: ^1.0
- psr/http-message: ^1.0
- psr/simple-cache: ^1.0
- psr/simple-cache-implementation: ^1.0
Requires (Dev)
- cache/filesystem-adapter: ^1.1
- friendsofphp/php-cs-fixer: ^3.0
- guzzlehttp/guzzle: ^7.0
- jetbrains/phpstorm-attributes: ^1.0
- nyholm/psr7: ^1.0
- phpstan/phpstan: ^0.12.90
- phpunit/phpunit: ^9.5
- rector/rector: ^0.11.32
- symfony/cache: ^5.0
- symfony/http-client: ^5.0
Suggests
- guzzlehttp/guzzle: A http client implementation (PSR-17 and PSR-18)
- nyholm/psr7: Needed when you use symfony/http-client
- symfony/http-client: A http client implementation (PSR-17 and PSR-18)
- dev-master
- v1.1.180
- v1.1.174
- v1.1.173
- v1.1.080
- v1.1.074
- v1.1.073
- v1.0.180
- v1.0.174
- v1.0.173
- v1.0.080
- v1.0.074
- v1.0.073
- v0.12.1.80
- v0.12.1.74
- v0.12.1.73
- v0.12.0.80
- v0.12.0.73
- v0.11.1.80
- v0.11.1.73
- v0.11.0.80
- v0.11.0.73
- v0.10.1.80
- v0.10.1.73
- v0.10.0.80
- v0.10.0.73
- v0.9.11.80
- v0.9.11.73
- v0.9.10.80
- v0.9.10.73
- v0.9.9.80
- v0.9.9.73
- v0.9.2.80
- v0.9.2.73
- v0.9.1.80
- v0.9.1.73
- v0.9.0
- dev-code-coverage
- dev-php-8.1
- dev-php-7.3
- dev-php-7.4
This package is auto-updated.
Last update: 2021-08-18 09:31:40 UTC
README
A PHP implementation of the Unleash protocol aka Feature Flags in GitLab.
You may also be interested in the Symfony Bundle for this package.
This implementation conforms to the official Unleash standards and implements all of Unleash features.
Unleash allows you to gradually release your app's feature before doing a full release based on multiple strategies like releasing to only specific users or releasing to a percentage of your user base. Read more in the above linked documentations.
Installation
composer require rikudou/unleash-sdk
Requires PHP 7.3 or newer.
You will also need some implementation of PSR-18 and PSR-17, for example Guzzle and PSR-16, for example Symfony Cache. Example:
composer require rikudou/unleash-sdk guzzlehttp/guzzle symfony/cache
or
composer require rikudou/unleash-sdk symfony/http-client nyholm/psr7 symfony/cache
Usage
The basic usage is getting the Unleash
object and checking for a feature:
<?php use Rikudou\Unleash\UnleashBuilder; $unleash = UnleashBuilder::create() ->withAppName('Some app name') ->withAppUrl('https://some-app-url.com') ->withInstanceId('Some instance id') ->build(); if ($unleash->isEnabled('some-feature-name')) { // do something }
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
.
<?php use Rikudou\Unleash\UnleashBuilder; use Rikudou\Unleash\Configuration\UnleashContext; $unleash = UnleashBuilder::create() ->withAppName('Some app name') ->withAppUrl('https://some-app-url.com') ->withInstanceId('Some instance id') ->build(); $context = new UnleashContext( currentUserId: 'some-user-id-from-app', ipAddress: '127.0.0.1', // will be populated automatically from $_SERVER if needed sessionId: 'sess-123456', // will be populated automatically via session_id() if needed ); // or using pre php 8 style: $context = (new UnleashContext()) ->setCurrentUserId('some-user-id-from-app') ->setIpAddress('127.0.0.1') ->setSessionId('sess-123456'); if ($unleash->isEnabled('some-feature', $context)) { // do something } // changing the default value for non-existent features if ($unleash->isEnabled('nonexistent-feature', $context, true)) { // do something }
Builder
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:
<?php use Rikudou\Unleash\UnleashBuilder; // both are the same $builder = new UnleashBuilder(); $builder = UnleashBuilder::create();
Required parameters
The app name, instance id and app url are required as per the specification.
<?php use Rikudou\Unleash\UnleashBuilder; $builder = UnleashBuilder::create() ->withAppName('Some app name') ->withAppUrl('https://some-app-url.com') ->withInstanceId('Some instance id');
If you're using Unleash v4 you also need to specify authorization key (API key), you can do so with custom header.
<?php use Rikudou\Unleash\UnleashBuilder; $builder = UnleashBuilder::create() ->withAppName('Some app name') ->withAppUrl('https://some-app-url.com') ->withInstanceId('Some instance id') ->withHeader('Authorization', 'my-api-key');
Optional parameters
Some optional parameters can be set, these include:
- http client implementation
- request factory implementation
- cache implementation (PSR-16)
- cache ttl
- available strategies
- http headers
If you use guzzlehttp/guzzle or symfony/http-client (in combination with nyholm/psr7), the http client and request factory will be created automatically, otherwise you need to provide an 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.
<?php use Cache\Adapter\Filesystem\FilesystemCachePool; use League\Flysystem\Adapter\Local; use League\Flysystem\Filesystem; use GuzzleHttp\Client; use GuzzleHttp\Psr7\HttpFactory; use Rikudou\Unleash\Stickiness\MurmurHashCalculator; use Rikudou\Unleash\Strategy\DefaultStrategyHandler; use Rikudou\Unleash\Strategy\GradualRolloutStrategyHandler; use Rikudou\Unleash\Strategy\IpAddressStrategyHandler; use Rikudou\Unleash\Strategy\UserIdStrategyHandler; use Rikudou\Unleash\UnleashBuilder; $builder = UnleashBuilder::create() ->withAppName('Some app name') ->withAppUrl('https://some-app-url.com') ->withInstanceId('Some instance id') // now the optional ones ->withHttpClient(new Client()) ->withRequestFactory(new HttpFactory()) ->withCacheHandler(new FilesystemCachePool( // example with using cache/filesystem-adapter new Filesystem( new Local(sys_get_temp_dir()), ), ), 30) // the second parameter is time to live in seconds ->withCacheTimeToLive(60) // you can also set the cache time to live separately // if you don't add any strategies, by default all strategies are added ->withStrategies( // this example includes all available strategies new DefaultStrategyHandler(), new GradualRolloutStrategyHandler(new MurmurHashCalculator()), new IpAddressStrategyHandler(), new UserIdStrategyHandler(), ) // add headers one by one, if you specify a header with the same name multiple times it will be replaced by the // latest value ->withHeader('My-Custom-Header', 'some-value') ->withHeader('Some-Other-Header', 'some-other-value') // you can specify multiple headers at the same time, be aware that this REPLACES all the headers ->withHeaders([ 'Yet-Another-Header' => 'and-another-value', ]);
Caching
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 30 seconds.
Cache implementations supported out of the box (meaning you don't need to configure anything):
<?php use Cache\Adapter\Filesystem\FilesystemCachePool; use League\Flysystem\Adapter\Local; use League\Flysystem\Filesystem; use Rikudou\Unleash\UnleashBuilder; $builder = UnleashBuilder::create() ->withCacheHandler(new FilesystemCachePool( // example with using cache/filesystem-adapter new Filesystem( new Local(sys_get_temp_dir()), ), )) ->withCacheTimeToLive(120); // you can set the cache handler explicitly to null to revert back to autodetection $builder = $builder ->withCacheHandler(null);
Strategies
Unleash servers can use multiple strategies for enabling or disabling features. Which strategy gets used is defined on the server. This implementation supports all non-deprecated v4 strategies except hostnames. More here.
Default strategy
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.
IP address strategy
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.
<?php use Rikudou\Unleash\UnleashBuilder; use Rikudou\Unleash\Configuration\UnleashContext; $unleash = UnleashBuilder::create() ->withAppName('Some app name') ->withAppUrl('https://some-app-url.com') ->withInstanceId('Some instance id') ->build(); // without context, using the auto detected IP $enabled = $unleash->isEnabled('some-feature'); // with context $context = new UnleashContext(ipAddress: $_SERVER['HTTP_X_FORWARDED_FOR']); // or pre php 8 style $context = (new UnleashContext()) ->setIpAddress($_SERVER['HTTP_X_FORWARDED_FOR']); $enabled = $unleash->isEnabled('some-feature', $context);
User ID strategy
Enables feature based on the user ID. The user ID can be any string. You must always provide your own user id via context.
<?php use Rikudou\Unleash\UnleashBuilder; use Rikudou\Unleash\Configuration\UnleashContext; $unleash = UnleashBuilder::create() ->withAppName('Some app name') ->withAppUrl('https://some-app-url.com') ->withInstanceId('Some instance id') ->build(); $context = new UnleashContext(currentUserId: 'some-user-id'); $enabled = $unleash->isEnabled('some-feature', $context);
Gradual rollout strategy
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 \Rikudou\Unleash\Stickiness\MurmurHashCalculator
<?php use Rikudou\Unleash\UnleashBuilder; use Rikudou\Unleash\Configuration\UnleashContext; $unleash = UnleashBuilder::create() ->withAppName('Some app name') ->withAppUrl('https://some-app-url.com') ->withInstanceId('Some instance id') ->build(); // assume the feature uses the default type which means that it will default to either session id (if session is started) // or randomly $unleash->isEnabled('some-feature'); // still using the default strategy but this time with user id (which is the first to be used if present) $context = new UnleashContext(currentUserId: 'some-user-id'); $unleash->isEnabled('some-feature', $context); // let's start the session to ensure the session id is used session_start(); $unleash->isEnabled('some-feature'); // or you can provide your own session id $context = new UnleashContext(sessionId: 'sess-123456'); $unleash->isEnabled('some-feature', $context); // assume the feature is set to use the user id, the first call returns false (no context given), the second // one returns true/false based on the user id $unleash->isEnabled('some-feature'); $context = new UnleashContext(currentUserId: 'some-user-id'); $unleash->isEnabled('some-feature', $context); // the same goes for session, assume the session isn't started yet and the feature is set to use the session type $unleash->isEnabled('some-feature'); // returns false because no session is available $context = new UnleashContext(sessionId: 'some-session-id'); $unleash->isEnabled('some-feature', $context); // works because you provided the session id manually session_start(); $unleash->isEnabled('some-feature'); // works because the session is started // lastly you can force the feature to use the random type which always works $unleash->isEnabled('some-feature');
Note: This library also implements some deprecated strategies, namely
gradualRolloutRandom
,gradualRolloutSessionId
andgradualRolloutUserId
which all alias to the Gradual rollout strategy.
Custom strategies
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.
<?php use Rikudou\Unleash\Strategy\AbstractStrategyHandler; use Rikudou\Unleash\DTO\Strategy; use Rikudou\Unleash\Configuration\Context; use Rikudou\Unleash\Strategy\DefaultStrategyHandler; class AprilFoolsStrategy extends AbstractStrategyHandler { public function __construct(private DefaultStrategyHandler $original) { } public function getStrategyName() : string { return 'aprilFools'; } public function isEnabled(Strategy $strategy, Context $context) : bool { $date = new DateTimeImmutable(); if ((int) $date->format('n') === 4 && (int) $date->format('j') === 1) { return (bool) random_int(0, 1); } return $this->original->isEnabled($strategy, $context); } }
Now you must instruct the builder to use your new strategy
<?php use Rikudou\Unleash\UnleashBuilder; use Rikudou\Unleash\Strategy\IpAddressStrategyHandler; $unleash = UnleashBuilder::create() ->withAppName('Some app name') ->withAppUrl('https://some-app-url.com') ->withInstanceId('Some instance id') ->withStrategy(new AprilFoolsStrategy()) // this will append your strategy to the existing list ->build(); // if you want to replace all strategies, use withStrategies() instead $unleash = UnleashBuilder::create() ->withAppName('Some app name') ->withAppUrl('https://some-app-url.com') ->withInstanceId('Some instance id') ->withStrategies(new AprilFoolsStrategy(), new IpAddressStrategyHandler()) // now the unleash object will have only the two strategies ->build();
Variants
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.
<?php use Rikudou\Unleash\DTO\DefaultVariant; use Rikudou\Unleash\UnleashBuilder; use Rikudou\Unleash\Configuration\UnleashContext; use Rikudou\Unleash\Enum\VariantPayloadType; use Rikudou\Unleash\DTO\DefaultVariantPayload; $unleash = UnleashBuilder::create() ->withAppName('Some app name') ->withAppUrl('https://some-app-url.com') ->withInstanceId('Some instance id') ->build(); $variant = $unleash->getVariant('nonexistentFeature'); assert($variant->isEnabled() === false); // getVariant() does isEnabled() call in the background meaning that it will return the default falsy variant // whenever isEnabled() returns false $variant = $unleash->getVariant('existingFeatureThatThisUserDoesNotHaveAccessTo'); assert($variant->isEnabled() === false); $variant = $unleash->getVariant('someFeature', new UnleashContext(currentUserId: '123')); if ($variant->isEnabled()) { $payload = $variant->getPayload(); if ($payload !== null) { if ($payload->getType() === VariantPayloadType::JSON) { $jsonData = $payload->fromJson(); } $stringPayload = $payload->getValue(); } } // providing custom default variant $variant = $unleash->getVariant('nonexistentFeature', fallbackVariant: new DefaultVariant( 'variantName', enabled: true, payload: new DefaultVariantPayload(VariantPayloadType::STRING, 'somePayload'), )); assert($variant->getPayload()->getValue() === 'somePayload');
Client registration
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.
<?php use Rikudou\Unleash\UnleashBuilder; $unleash = UnleashBuilder::create() ->withAppName('Some App Name') ->withAppUrl('https://somewhere.com') ->withInstanceId('some-instance-id') ->withAutomaticRegistrationEnabled(false) ->build(); // event though the client will not attempt to register, you can still use isEnabled() $unleash->isEnabled('someFeature'); // if you want to register manually $unleash->register(); // you can call the register method multiple times, the Unleash server doesn't mind $unleash->register(); $unleash->register();
Metrics
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:
- user visits your site and this sdk gets triggered, no metric has been sent
- after five seconds user visits another page where again this sdk gets triggered, no metric sent
- user waits one minute before doing anything, no one else is accessing your site
- after one minute user visits another page, the metrics have been sent to the Unleash server
In the example above the metric bundle gets sent after 1 minute and 5 seconds because there was no one to trigger the code.
<?php use Rikudou\Unleash\UnleashBuilder; $unleash = UnleashBuilder::create() ->withAppName('Some App Name') ->withAppUrl('https://somewhere.com') ->withInstanceId('some-instance-id') ->withMetricsEnabled(false) // turn off metric sending ->withMetricsEnabled(true) // turn on metric sending ->withMetricsInterval(10_000) // interval in milliseconds (10 seconds) ->build(); // the metric will be collected but not sent immediately $unleash->isEnabled('test'); sleep(10); // now the metrics will get sent $unleash->isEnabled('test');
Constraints
Constraints are supported by this SDK and will be handled correctly by Unleash::isEnabled()
if present.
GitLab specifics
- In GitLab you have to use the provided instance id, you cannot create your own.
- No authorization header is necessary.
- Instead of app name you need to specify the GitLab environment.
- For this purpose you can use
withGitlabEnvironment()
method in builder, it's an alias towithAppName()
but communicates the intent better.
- For this purpose you can use
- GitLab doesn't use registration system, you can set the SDK to disable automatic registration and save one http call.
- GitLab doesn't read metrics, you can set the SDK to disable sending them and save some http calls.
<?php use Rikudou\Unleash\UnleashBuilder; $gitlabUnleash = UnleashBuilder::createForGitlab() ->withInstanceId('H9sU9yVHVAiWFiLsH2Mo') // generated in GitLab ->withAppUrl('https://git.example.com/api/v4/feature_flags/unleash/1') ->withGitlabEnvironment('Production') ->build(); // the above is equivalent to $gitlabUnleash = UnleashBuilder::create() ->withInstanceId('H9sU9yVHVAiWFiLsH2Mo') ->withAppUrl('https://git.example.com/api/v4/feature_flags/unleash/1') ->withGitlabEnvironment('Production') ->withAutomaticRegistrationEnabled(false) ->withMetricsEnabled(false) ->build();