PHP code example of zenmanage / zenmanage-php

1. Go to this page and download the library: Download zenmanage/zenmanage-php 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/ */

    

zenmanage / zenmanage-php example snippets


use Zenmanage\Config\ConfigBuilder;
use Zenmanage\Zenmanage;

$zenmanage = new Zenmanage(
    ConfigBuilder::create()
    ->withEnvironmentToken('srv_your_server_key_here')
        ->build()
);

if ($zenmanage->flags()->single('new-dashboard')->isEnabled()) {
    // Show new dashboard
    return view('dashboard-v2');
}

// Show old dashboard
return view('dashboard');

// Check if user has access to beta features
$context = Context::single('user', $user->id, $user->name);

$betaAccess = $zenmanage->flags()
    ->withContext($context)
    ->single('beta-program')
    ->isEnabled();

if ($betaAccess) {
    // User is in beta program
    $features = $this->getBetaFeatures();
}

$context = Context::fromArray([
    'type' => 'user',
    'identifier' => $user->id,
    'name' => $user->name,
    'attributes' => [
        ['key' => 'country', 'values' => [['value' => $user->country]]],
    ],
]);

$variant = $zenmanage->flags()
    ->withContext($context)
    ->single('checkout-flow')
    ->asString();

if ($variant === 'one-page') {
    return view('checkout.onepage');
} else {
    return view('checkout.multipage');
}

use Zenmanage\Flags\Context\Context;

// Just provide a context with an identifier — the SDK does the rest
$context = Context::single('user', $user->id);

$flag = $zenmanage->flags()
    ->withContext($context)
    ->single('new-checkout-flow');

if ($flag->isEnabled()) {
    // This user is in the rollout percentage
    return view('checkout.new');
}

// This user is outside the rollout
return view('checkout.classic');

$context = Context::fromArray([
    'type' => 'organization',
    'identifier' => $user->organization->id,
    'name' => $user->organization->name,
    'attributes' => [
        ['key' => 'plan', 'values' => [['value' => $user->organization->plan]]],
    ],
]);

$advancedReports = $zenmanage->flags()
    ->withContext($context)
    ->single('advanced-reports')
    ->isEnabled();

if ($advancedReports) {
    return $this->getAdvancedReports();
}

// Get configuration values from flags
$apiTimeout = $zenmanage->flags()
    ->single('api-timeout', 5000)  // Default 5000ms
    ->asNumber();

$maxUploadSize = $zenmanage->flags()
    ->single('max-upload-mb', 10)
    ->asNumber();

$welcomeMessage = $zenmanage->flags()
    ->single('welcome-text', 'Welcome!')
    ->asString();

// Quickly disable a problematic feature via dashboard
if ($zenmanage->flags()->single('new-payment-processor', false)->isEnabled()) {
    return $this->processWithNewSystem($payment);
} else {
    return $this->processWithLegacySystem($payment);
}

// app/Providers/ZenmanageServiceProvider.php
namespace App\Providers;

use Illuminate\Support\ServiceProvider;
use Zenmanage\Config\ConfigBuilder;
use Zenmanage\Zenmanage;

class ZenmanageServiceProvider extends ServiceProvider
{
    public function register()
    {
        $this->app->singleton(Zenmanage::class, function ($app) {
            return new Zenmanage(
                ConfigBuilder::create()
                    ->withEnvironmentToken(config('services.zenmanage.token'))
                    ->withCacheBackend('filesystem')
                    ->withCacheDirectory(storage_path('framework/cache/zenmanage'))
                    ->withCacheTtl(3600)
                    ->build()
            );
        });
    }
}

// config/services.php
return [
    // ...
    'zenmanage' => [
        'token' => env('ZENMANAGE_TOKEN'),
    ],
];

class DashboardController extends Controller
{
    public function __construct(private Zenmanage $zenmanage) {}

    public function index(Request $request)
    {
        $context = Context::single('user', $request->user()->email);
        
        $useNewDashboard = $this->zenmanage->flags()
            ->withContext($context)
            ->single('new-dashboard', false)
            ->isEnabled();

        return $useNewDashboard 
            ? view('dashboard-v2')
            : view('dashboard');
    }
}

// src/Factory/ZenmanageFactory.php
namespace App\Factory;

use Zenmanage\Config\ConfigBuilder;
use Zenmanage\Zenmanage;

class ZenmanageFactory
{
    public static function create(string $token, string $cacheDir): Zenmanage
    {
        return new Zenmanage(
            ConfigBuilder::create()
                ->withEnvironmentToken($token)
                ->withCacheBackend('filesystem')
                ->withCacheDirectory($cacheDir)
                ->build()
        );
    }
}

// bootstrap.php or similar
$zenmanage = new Zenmanage(
    ConfigBuilder::create()
        ->withEnvironmentToken($_ENV['ZENMANAGE_TOKEN'])
        ->withCacheBackend('filesystem')
        ->withCacheDirectory(__DIR__ . '/cache/zenmanage')
        ->build()
);

// Make available globally (if needed)
$GLOBALS['zenmanage'] = $zenmanage;
// Or use a registry pattern, DI container, etc.

use Zenmanage\Flags\Context\Context;

// Target by user ID with name
$context = Context::single('user', $user->id, $user->name);

// Target by organization
$context = Context::single('organization', $company->id, $company->name);

// Target by user with just ID
$context = Context::single('user', $user->id);

$context = Context::fromArray([
    'type' => 'user',
    'identifier' => $user->id,
    'name' => $user->name,
    'attributes' => [
        ['key' => 'organization', 'values' => [['value' => $user->company->slug]]],
        ['key' => 'plan', 'values' => [['value' => $user->subscription->plan]]],
        ['key' => 'role', 'values' => [['value' => $user->role]]],
        ['key' => 'country', 'values' => [['value' => $user->country]]],
    ],
]);

$premiumFeatures = $zenmanage->flags()
    ->withContext($context)
    ->single('premium-dashboard')
    ->isEnabled();

// Rule: "Block these specific IPs"
// Selector: "segment", Values: [{"type": "user", "identifier": "140.248.31.37"}]

$context = Context::single('user', '140.248.31.37', 'Blocked User');
$result = $zenmanage->flags()
    ->withContext($context)
    ->single('allow-feature', true)
    ->isEnabled(); // Returns: false (matched segment)

// Rule: "Enable for specific users"
// Selector: "context", Values: [{"type": "user", "identifier": "john-doe"}]

$context = Context::single('user', 'john-doe', 'John Doe');
$result = $zenmanage->flags()
    ->withContext($context)
    ->single('beta-feature', false)
    ->isEnabled(); // Returns: true (matched context)

// Rule: "Enable for enterprise plans"
// Selector: "attribute", Subtype: "plan", Values: ["enterprise"]

$context = Context::fromArray([
    'type' => 'user',
    'identifier' => 'user-123',
    'name' => 'Jane Doe',
    'attributes' => [
        ['key' => 'plan', 'values' => [['value' => 'enterprise']]],
        ['key' => 'country', 'values' => [['value' => 'US']]],
    ],
]);

$result = $zenmanage->flags()
    ->withContext($context)
    ->single('premium-features', false)
    ->isEnabled(); // Returns: true (plan matched)

// If 'new-checkout' doesn't exist, returns true
$enabled = $zenmanage->flags()
    ->single('new-checkout', true)
    ->isEnabled();

// Configuration value with fallback
$timeout = $zenmanage->flags()
    ->single('api-timeout', 5000)
    ->asNumber();

use Zenmanage\Flags\DefaultsCollection;

$defaults = DefaultsCollection::fromArray([
    'new-ui' => true,
    'max-upload-size' => 10,
    'welcome-message' => 'Welcome to our app!',
    'feature-x' => false,
]);

$flags = $zenmanage->flags()->withDefaults($defaults);

// All these will use defaults if flags don't exist
$newUI = $flags->single('new-ui')->isEnabled();
$maxSize = $flags->single('max-upload-size')->asNumber();
$message = $flags->single('welcome-message')->asString();

$defaults = DefaultsCollection::fromArray(['timeout' => 3000]);

// Uses API value if exists, otherwise inline (5000), then collection (3000)
$timeout = $zenmanage->flags()
    ->withDefaults($defaults)
    ->single('timeout', 5000)
    ->asNumber();

// First call fetches from API
$newUI = $zenmanage->flags()->single('new-ui')->isEnabled();

// Subsequent calls use memory cache (same request)
$newUI2 = $zenmanage->flags()->single('new-ui')->isEnabled(); // Instant

$config = ConfigBuilder::create()
    ->withEnvironmentToken('srv_your_server_key')
    ->withCacheBackend('filesystem')
    ->withCacheDirectory('/var/cache/zenmanage')
    ->withCacheTtl(300) // 5 minutes
    ->build();

// 5 minutes (good for rapid development)
->withCacheTtl(300)

// 1 hour (good for production)
->withCacheTtl(3600)

// 1 day (good for stable flags)
->withCacheTtl(86400)

// Always fetch fresh from API
$config = ConfigBuilder::create()
    ->withCacheBackend('null')
    ->build();

$zenmanage->flags()->refreshRules();

use Psr\Log\LoggerInterface;

$config = ConfigBuilder::create()
    ->withEnvironmentToken('srv_your_server_key')
    ->withLogger($yourLogger)
    ->build();

use Monolog\Logger;
use Monolog\Handler\StreamHandler;

$logger = new Logger('zenmanage');
$logger->pushHandler(new StreamHandler('path/to/zenmanage.log', Logger::DEBUG));

$config = ConfigBuilder::create()
    ->withLogger($logger)
    ->build();

// Bad - will throw exception if flag doesn't exist
$showNewUI = $zenmanage->flags()->single('new-ui')->isEnabled();

// Good - falls back to false if anything goes wrong
$showNewUI = $zenmanage->flags()->single('new-ui', false)->isEnabled();

try {
    $premiumEnabled = $zenmanage->flags()
        ->withContext($context)
        ->single('premium-features', false) // Default to false
        ->isEnabled();
        
    if ($premiumEnabled) {
        return $this->showPremiumDashboard();
    }
} catch (ZenmanageException $e) {
    // Log error but continue with default behavior
    $this->logger->warning('Flag check failed', ['error' => $e->getMessage()]);
    $premiumEnabled = false;
}

return $this->showStandardDashboard();

public function test_premium_users_see_dashboard()
{
    $zenmanage = new Zenmanage(
        ConfigBuilder::create()
            ->withEnvironmentToken('test-token')
            ->withCacheBackend('null') // No caching in tests
            ->build()
    );
    
    $defaults = DefaultsCollection::fromArray([
        'premium-dashboard' => true,
    ]);
    
    $enabled = $zenmanage->flags()
        ->withDefaults($defaults)
        ->single('premium-dashboard')
        ->isEnabled();
        
    $this->assertTrue($enabled);
}

use PHPUnit\Framework\TestCase;
use Zenmanage\Flags\FlagManagerInterface;
use Zenmanage\Flags\Flag;

class CheckoutTest extends TestCase
{
    public function test_new_checkout_flow()
    {
        $flagManager = $this->createMock(FlagManagerInterface::class);
        $flagManager->method('single')
            ->willReturn(new Flag('new-checkout', 'New Checkout', true));
            
        $checkout = new CheckoutService($flagManager);
        
        $result = $checkout->processPayment($order);
        
        $this->assertTrue($result->usedNewFlow());
    }
}

public function test_feature_disabled_shows_old_ui()
{
    $defaults = DefaultsCollection::fromArray(['new-ui' => false]);
    
    $flag = $this->zenmanage->flags()
        ->withDefaults($defaults)
        ->single('new-ui');
        
    $this->assertFalse($flag->isEnabled());
}

public function test_feature_enabled_shows_new_ui()
{
    $defaults = DefaultsCollection::fromArray(['new-ui' => true]);
    
    $flag = $this->zenmanage->flags()
        ->withDefaults($defaults)
        ->single('new-ui');
        
    $this->assertTrue($flag->isEnabled());
}
bash
composer 
bash
composer