PHP code example of phputil / flags

1. Go to this page and download the library: Download phputil/flags library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

phputil / flags example snippets



use phputil\flags\FlagManager;

// By default, it uses a storage-based strategy with an in-memory storage
$flag = new FlagManager();

if ( $flag->isEnabled( 'my-cool-feature' ) ) {
    echo 'Cool feature available!', PHP_EOL;
} else {
    echo 'Not-so-cool feature here', PHP_EOL;
}

// ...
use phputil\flags\FlagVerificationStrategy;

$flag = new FlagManager();

$myLuckBasedStrategy = new class implements FlagVerificationStrategy {
    function isEnabled( string $flag ): bool {
        return rand( 1, 100 ) >= 50; // 50% chance
    }
};

if ( $flag->isEnabled( 'my-cool-feature', [ $myLuckBasedStrategy ] ) ) {
    echo 'Cool feature available!', PHP_EOL;
} else {
    echo 'Not-so-cool feature here', PHP_EOL;
}

$flag = new FlagManager( null, [ $myLuckBasedStrategy ] );

if ( $flag->isEnabled( 'my-cool-feature' ) ) {
    ...

$flag->enable( 'my-cool-feature' );
$flag->disable( 'my-cool-feature' );
$flag->setEnable( 'my-cool-feature', true /* or false */ );

$flag->remove( 'my-cool-feature' );

$flagData = $flag->getStorage()->get( 'my-cool-feature' ); // null if not found

// ...
use phputil\flags\FlagListener;
use phputil\flags\FlagData;

$myListener = new class implements FlagListener {
  public function notify( string $event, FlagData $flagData ): void {
    if ( $event === 'change' ) {
        echo 'Flag ', $flagData->key, ' is now ', $flagData->enabled ? 'enabled': 'disabled', PHP_EOL;
    } else if ( $event === 'removal' ) {
        echo 'Flag ', $flagData->key, ' was removed.', PHP_EOL;
    }
  }
};

$flag->addListener( $myListener ); // v0.5.0+
// or $flag->getListeners()->add( $myListener );

$flag->enable( 'my-cool-feature' ); // Notify the listener

$storage = /* Create your storage here, e.g. new InMemoryStorage() */;
$flag = new FlagManager( $storage );

$strategies = [ /* pass your strategies here   */ ];
$flag = new FlagManager( null, $strategies );

$flag->addListener( $myListener ); // v0.5.0+
// or $flag->getListeners()->add( $myListener );