### Install Optimizely PHP SDK using Composer Source: https://context7.com/optimizely/php-sdk/llms.txt This snippet shows the Composer command to install the Optimizely PHP SDK. Composer is a dependency manager for PHP and is required for this installation. ```bash composer require optimizely/optimizely-sdk ``` -------------------------------- ### Install Optimizely PHP SDK via Composer Source: https://github.com/optimizely/php-sdk/blob/master/README.md This snippet shows the command to install the Optimizely PHP SDK using Composer, the dependency manager for PHP. Ensure Composer is installed and accessible in your project's directory. ```bash php composer.phar require optimizely/optimizely-sdk ``` -------------------------------- ### Run Unit Tests (Bash) Source: https://github.com/optimizely/php-sdk/blob/master/README.md Command to execute all unit tests for the Optimizely PHP SDK using PHPUnit. Ensure you have the necessary dependencies installed via Composer. ```bash ./vendor/bin/phpunit ``` -------------------------------- ### Get Optimizely Config in PHP Source: https://context7.com/optimizely/php-sdk/llms.txt Retrieve the complete project configuration, including features, experiments, variations, variables, events, and audiences. The configuration can be iterated through and exported to a JSON file. This is useful for programmatic access to project settings. ```php getOptimizelyConfig(); if (!$config) { echo "SDK not initialized\n"; exit; } // Get config metadata echo "Environment: {$config->getEnvironmentKey()}\n"; echo "SDK Key: {$config->getSdkKey()}\n"; echo "Revision: {$config->getRevision()}\n"; // Iterate through all features $featuresMap = $config->getFeaturesMap(); foreach ($featuresMap as $flagKey => $feature) { echo "\nFeature: {$flagKey}\n"; echo " ID: {$feature->getId()}\n"; // Get feature variables $variablesMap = $feature->getVariablesMap(); foreach ($variablesMap as $varKey => $variable) { echo " Variable: {$varKey} = {$variable->getValue()} ({$variable->getType()})\n"; } // Get experiment rules $experimentRules = $feature->getExperimentRules(); foreach ($experimentRules as $experiment) { echo " Experiment: {$experiment->getKey()}\n"; // Get variations $variationsMap = $experiment->getVariationsMap(); foreach ($variationsMap as $varKey => $variation) { echo " Variation: {$varKey}\n"; } } } // Get all events $events = $config->getEvents(); foreach ($events as $event) { echo "Event: {$event->getKey()} (ID: {$event->getId()})\n"; } // Get all audiences $audiences = $config->getAudiences(); foreach ($audiences as $audience) { echo "Audience: {$audience->getName()} - {$audience->getConditions()}\n"; } // Export to JSON $configJson = json_encode($config, JSON_PRETTY_PRINT); file_put_contents('optimizely-config-export.json', $configJson); ?> ``` -------------------------------- ### Get Feature Variables - PHP Source: https://context7.com/optimizely/php-sdk/llms.txt Retrieve individual feature variable values for a given user and attributes using various type-specific methods (Integer, Boolean, String, Double, JSON). This is a legacy method for accessing feature variables. It requires the Optimizely client instance, feature key, variable key, user ID, and user attributes as input. ```php 'gold']; // Get different variable types $maxResults = $optimizelyClient->getFeatureVariableInteger( 'search_feature', 'max_results', $userId, $attributes ); $enableSpellcheck = $optimizelyClient->getFeatureVariableBoolean( 'search_feature', 'enable_spellcheck', $userId, $attributes ); $sortAlgorithm = $optimizelyClient->getFeatureVariableString( 'search_feature', 'sort_algorithm', $userId, $attributes ); $relevanceWeight = $optimizelyClient->getFeatureVariableDouble( 'search_feature', 'relevance_weight', $userId, $attributes ); $filterConfig = $optimizelyClient->getFeatureVariableJSON( 'search_feature', 'filter_config', $userId, $attributes ); // Use retrieved variables echo "Max results: {$maxResults}\n"; echo "Spellcheck: " . ($enableSpellcheck ? 'enabled' : 'disabled') . "\n"; echo "Sort algorithm: {$sortAlgorithm}\n"; echo "Relevance weight: {$relevanceWeight}\n"; echo "Filter config: " . json_encode($filterConfig) . "\n"; ?> ``` -------------------------------- ### Initialize Optimizely Client with SDK Key Source: https://context7.com/optimizely/php-sdk/llms.txt Initializes the Optimizely client using an SDK key. This method automatically fetches and manages the project datafile. It requires the `OptimizelyFactory` class and returns a client instance that can be verified for readiness. ```php getOptimizelyConfig()) { echo "SDK initialized successfully\n"; } ``` -------------------------------- ### Initialize Optimizely Client with Datafile Source: https://github.com/optimizely/php-sdk/blob/master/README.md This PHP code demonstrates how to initialize the Optimizely client by providing the datafile directly. The datafile contains the configuration for your Optimizely experiments and feature flags. ```php >); ``` -------------------------------- ### Initialize Optimizely Client with SDK Key Source: https://github.com/optimizely/php-sdk/blob/master/README.md This PHP code shows how to create an Optimizely client using the OptimizelyFactory. This method allows initialization with an SDK key, an optional fallback datafile, and an optional datafile access token, internally creating an HTTPProjectConfigManager. ```php >, <> ); ``` -------------------------------- ### Initialize Optimizely Client with Static Datafile Source: https://context7.com/optimizely/php-sdk/llms.txt Initializes the Optimizely client with a static datafile provided as a JSON string. This method allows for direct control over the datafile content and can integrate with custom logging using Monolog. It requires the `Optimizely` class and `DefaultLogger` from the SDK. ```php fetch(); ``` -------------------------------- ### Implement User Profile Service for Optimizely PHP SDK Source: https://context7.com/optimizely/php-sdk/llms.txt This code demonstrates how to implement a custom user profile service using a database for persistent user bucketing. It implements the UserProfileServiceInterface and uses PDO for database interactions. This ensures users consistently receive the same experiment variations across sessions. ```php db = $databaseConnection; } public function lookup($userId) { $stmt = $this->db->prepare( "SELECT profile_data FROM user_profiles WHERE user_id = ?" ); $stmt->execute([$userId]); $result = $stmt->fetch(PDO::FETCH_ASSOC); if ($result) { return json_decode($result['profile_data'], true); } return null; } public function save($userProfile) { $userId = $userProfile['user_id']; $profileData = json_encode($userProfile); $stmt = $this->db->prepare( "INSERT INTO user_profiles (user_id, profile_data, updated_at) VALUES (?, ?, NOW()) ON DUPLICATE KEY UPDATE profile_data = ?, updated_at = NOW()" ); $stmt->execute([$userId, $profileData, $profileData]); } } // Initialize SDK with user profile service $db = new PDO('mysql:host=localhost;dbname=myapp', 'user', 'password'); $userProfileService = new DatabaseUserProfileService($db); $optimizelyClient = new Optimizely( $datafile, null, null, null, false, $userProfileService ); // Users will now get consistent variations across sessions $decision = $optimizelyClient->activate('homepage_test', 'user_123', []); // This user will always see the same variation ``` -------------------------------- ### Initialize Optimizely Client with Custom Config Manager Source: https://github.com/optimizely/php-sdk/blob/master/README.md This PHP code demonstrates initializing the Optimizely client with a custom implementation of ProjectConfigManagerInterface, specifically HTTPProjectConfigManager. This provides more control over how the project configuration is fetched and managed. ```php >); $optimizely = new Optimizely( <>, null, null, null, false, null, $configManager ); ``` -------------------------------- ### Initialize HTTPProjectConfigManager Source: https://github.com/optimizely/php-sdk/blob/master/README.md This PHP code shows how to instantiate the HTTPProjectConfigManager, which is an implementation of ProjectConfigManagerInterface. This manager is responsible for fetching the project datafile via HTTP requests. ```php >); ``` -------------------------------- ### Activate Experiment - PHP Source: https://context7.com/optimizely/php-sdk/llms.txt Activate a user in an A/B experiment and determine which variation they are assigned to. This legacy method automatically sends an impression event. It requires the Optimizely client instance, experiment key, user ID, and user attributes. The output is the variation key assigned to the user, or null if the user is not bucketed. ```php 'google', 'device_type' => 'mobile' ]; // Activate experiment (sends impression event automatically) $variationKey = $optimizelyClient->activate( 'homepage_redesign_test', $userId, $attributes ); if ($variationKey === 'variation_a') { echo "Show variant A homepage\n"; // Render variant A } elseif ($variationKey === 'variation_b') { echo "Show variant B homepage\n"; // Render variant B } else { echo "User not bucketed into experiment\n"; // Show control/default experience } ?> ``` -------------------------------- ### Evaluate All Feature Flags with decideAll in PHP Source: https://context7.com/optimizely/php-sdk/llms.txt Demonstrates how to evaluate all feature flags available in the project for a given user. This method can be optimized to only return enabled flags. It requires a user context and optionally accepts OptimizelyDecideOptions. ```php createUserContext('user_202', [ 'beta_tester' => true, 'region' => 'EU' ]); // Get all flags, only return enabled ones $options = [OptimizelyDecideOption::ENABLED_FLAGS_ONLY]; $allDecisions = $userContext->decideAll($options); echo "Enabled flags for user:\n"; foreach ($allDecisions as $flagKey => $decision) { echo "- {$flagKey}: {$decision->getVariationKey()}\n"; // Access variables for each enabled flag $variables = $decision->getVariables(); if (!empty($variables)) { echo " Variables: " . json_encode($variables) . "\n"; } } ?> ``` -------------------------------- ### Evaluate Multiple Feature Flags with decideForKeys in PHP Source: https://context7.com/optimizely/php-sdk/llms.txt Shows how to evaluate multiple feature flags in a single call using the `decideForKeys` method. This is an efficient way to retrieve the status and variations for several flags at once. It requires a user context and an array of flag keys. ```php createUserContext('user_101', [ 'device_type' => 'mobile', 'app_version' => '2.5.0' ]); // Get decisions for multiple flags $flagKeys = ['new_ui', 'dark_mode', 'push_notifications']; $decisions = $userContext->decideForKeys($flagKeys); // Process each decision foreach ($decisions as $flagKey => $decision) { if ($decision->getEnabled()) { echo "{$flagKey} is enabled with variation: {$decision->getVariationKey()}\n"; // Access specific variables per flag $variables = $decision->getVariables(); if ($flagKey === 'new_ui') { $theme = $variables['theme'] ?? 'light'; echo "UI theme: {$theme}\n"; } } } ?> ``` -------------------------------- ### Track Conversion Events in PHP with Optimizely SDK Source: https://context7.com/optimizely/php-sdk/llms.txt Illustrates how to send conversion events for experiment metrics and goal tracking using the Optimizely PHP SDK. Events can be tracked with or without custom event tags (metadata). This method can be called via a user context or directly via the Optimizely client. ```php createUserContext('user_303', [ 'account_age_days' => 45, 'ltv' => 299.99 ]); // Simple event tracking $userContext->trackEvent('purchase_completed'); // Track with event tags (custom metadata) $eventTags = [ 'revenue' => 129.99, 'product_id' => 'SKU-12345', 'quantity' => 2, 'currency' => 'USD', 'category' => 'electronics' ]; $userContext->trackEvent('add_to_cart', $eventTags); // Direct tracking via client (alternative method) $optimizelyClient->track( 'form_submitted', 'user_404', ['page' => 'checkout', 'step' => 3], ['form_type' => 'payment', 'fields_count' => 8] ); ?> ``` -------------------------------- ### Add Apache 2.0 License Header to PHP Code Source: https://github.com/optimizely/php-sdk/blob/master/CONTRIBUTING.md This code snippet provides the standard Apache 2.0 license header required for contributions to the Optimizely PHP SDK. It includes placeholders for copyright year and contributors. Ensure the YEAR is updated to reflect the contribution year(s). ```php /**************************************************************************** * Copyright YEAR, Optimizely, Inc. and contributors * * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * * See the License for the specific language governing permissions and * limitations under the License. ***************************************************************************/ ``` -------------------------------- ### Control Decision Behavior with OptimizelyDecideOptions in PHP Source: https://context7.com/optimizely/php-sdk/llms.txt Demonstrates how to control the decision-making process for feature flags using OptimizelyDecideOptions. This allows for customization of decision outcomes, such as including reasons, disabling impression events, or excluding feature variables. It requires the Optimizely SDK and a user context. ```php createUserContext('user_789', [ 'age' => 35, 'subscription' => 'premium' ]); // Apply multiple decide options $options = [ OptimizelyDecideOption::INCLUDE_REASONS, // Include decision reasons OptimizelyDecideOption::DISABLE_DECISION_EVENT, // Don't send impression event OptimizelyDecideOption::EXCLUDE_VARIABLES, // Exclude feature variables ]; $decision = $userContext->decide('recommendation_engine', $options); // Check reasons for debugging foreach ($decision->getReasons() as $reason) { echo "Decision reason: {$reason}\n"; } // Variables are empty due to EXCLUDE_VARIABLES option var_dump($decision->getVariables()); // [] ?> ``` -------------------------------- ### Access Optimizely Client's Config Manager Source: https://github.com/optimizely/php-sdk/blob/master/README.md This PHP snippet illustrates how to retrieve the configuration manager instance from an initialized Optimizely client. The config manager is responsible for managing the project's configuration data. ```php configManager; ``` -------------------------------- ### Implement Custom Event Dispatcher for Optimizely PHP SDK Source: https://context7.com/optimizely/php-sdk/llms.txt This snippet shows how to create a custom event dispatcher that batches events before sending them to an analytics endpoint. It implements the EventDispatcherInterface and uses cURL for sending POST requests. Dependencies include the Optimizely PHP SDK. ```php analyticsEndpoint = $analyticsEndpoint; $this->batchSize = $batchSize; } public function dispatchEvent(LogEvent $event) { // Add to queue $this->eventQueue[] = [ 'url' => $event->getUrl(), 'params' => $event->getParams(), 'http_verb' => $event->getHttpVerb(), 'headers' => $event->getHeaders() ]; // Flush if batch size reached if (count($this->eventQueue) >= $this->batchSize) { $this->flush(); } } public function flush() { if (empty($this->eventQueue)) { return; } // Send batched events to analytics platform $ch = curl_init($this->analyticsEndpoint); curl_setopt($ch, CURLOPT_POST, true); curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($this->eventQueue)); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']); curl_exec($ch); curl_close($ch); $this->eventQueue = []; } } // Use custom dispatcher $dispatcher = new BatchEventDispatcher('https://analytics.example.com/batch', 20); $optimizelyClient = new Optimizely( $datafile, $dispatcher ); // Events are now batched and sent to custom endpoint ``` -------------------------------- ### Check Feature Enabled Status in PHP (Legacy) Source: https://context7.com/optimizely/php-sdk/llms.txt Shows the legacy method for checking if a feature flag is enabled for a specific user with given attributes. It also demonstrates how to retrieve a list of all features enabled for a user. This method uses the Optimizely client directly. ```php 'chrome', 'os' => 'macos', 'screen_width' => 1920 ]; // Check if feature is enabled $isEnabled = $optimizelyClient->isFeatureEnabled('advanced_search', $userId, $attributes); if ($isEnabled) { echo "Advanced search is enabled\n"; // Show advanced search UI } else { echo "Advanced search is disabled\n"; // Show basic search UI } // Get all enabled features for user $enabledFeatures = $optimizelyClient->getEnabledFeatures($userId, $attributes); echo "Enabled features: " . implode(', ', $enabledFeatures) . "\n"; ?> ``` -------------------------------- ### Make Feature Flag Decision Source: https://context7.com/optimizely/php-sdk/llms.txt Evaluates a feature flag for a user context and retrieves comprehensive decision information. This includes checking if the feature is enabled, the variation key, feature variables, rule key, flag key, and decision reasons. Feature variables can be accessed and used for dynamic behavior. ```php createUserContext($userId, ['country' => 'CA']); // Basic decision $decision = $userContext->decide('new_checkout_flow'); // Access decision properties $isEnabled = $decision->getEnabled(); // bool: true/false $variationKey = $decision->getVariationKey(); // string: 'treatment' or 'control' $variables = $decision->getVariables(); // array: all feature variables $ruleKey = $decision->getRuleKey(); // string: experiment/rollout rule key $flagKey = $decision->getFlagKey(); // string: 'new_checkout_flow' $reasons = $decision->getReasons(); // array: decision reasons (if enabled) // Use variables $buttonColor = $variables['button_color'] ?? 'blue'; $maxRetries = $variables['max_retries'] ?? 3; if ($isEnabled) { echo "Feature enabled with variation: {$variationKey}\n"; echo "Button color: {$buttonColor}\n"; } ``` -------------------------------- ### Lint and Beautify PHP Code with Composer Source: https://github.com/optimizely/php-sdk/blob/master/CONTRIBUTING.md Commands to lint and autocorrect code style issues in the Optimizely PHP SDK using Composer scripts. `composer lint` checks for style compliance, while `composer beautify` attempts to automatically fix detected errors based on configured rules. ```bash composer lint composer beautify ``` -------------------------------- ### Integrate Custom Logger with Optimizely PHP SDK Source: https://context7.com/optimizely/php-sdk/llms.txt Integrate custom logging solutions with the Optimizely PHP SDK by implementing the LoggerInterface or using Monolog. This allows the SDK's logs to be directed to your preferred logging system for monitoring and debugging. ```php logFile = $logFile; } public function log($level, $message) { $timestamp = date('Y-m-d H:i:s'); $logEntry = "[{$timestamp}] [{$level}] {$message}\n"; file_put_contents($this->logFile, $logEntry, FILE_APPEND); } } // Use custom logger $logger = new CustomAppLogger('/var/log/optimizely.log'); $optimizelyClient = new Optimizely( $datafile, null, $logger ); // Or use Monolog with custom handlers use Monolog\Handler\StreamHandler; use Monolog\Handler\FirePHPHandler; use Optimizely\Logger\DefaultLogger; $monologLogger = new Logger('optimizely'); $monologLogger->pushHandler(new StreamHandler('/var/log/optimizely.log', Logger::DEBUG)); $monologLogger->pushHandler(new FirePHPHandler()); $optimizelyLogger = new DefaultLogger($monologLogger); $optimizelyClient = new Optimizely( $datafile, null, $optimizelyLogger ); ``` -------------------------------- ### Create Optimizely User Context Source: https://context7.com/optimizely/php-sdk/llms.txt Creates a user context for a specific user ID, including optional attributes. This context is used for personalized decision-making. Attributes can be updated dynamically after creation using the `setAttribute` method. ```php 28, 'country' => 'US', 'is_premium' => true, 'account_type' => 'enterprise' ]; $userContext = $optimizelyClient->createUserContext($userId, $attributes); // Update attributes dynamically $userContext->setAttribute('plan_tier', 'gold'); $userContext->setAttribute('feature_access_level', 5); ``` -------------------------------- ### Set Forced Decision - PHP Source: https://context7.com/optimizely/php-sdk/llms.txt Override experiment or feature flag decisions for specific users to test particular variations. This involves creating a user context, defining decision contexts (for flags or experiments with specific rules), and setting forced decisions. It allows for granular control over testing and debugging. Requires Optimizely SDK, user ID, attributes, and decision context objects. ```php createUserContext('qa_user_001', [ 'environment' => 'staging' ]); // Force specific variation for a flag $context = new OptimizelyDecisionContext('checkout_flow', null); $forcedDecision = new OptimizelyForcedDecision('variation_express_checkout'); $userContext->setForcedDecision($context, $forcedDecision); // Now this user will always get 'variation_express_checkout' $decision = $userContext->decide('checkout_flow'); echo "Forced variation: {$decision->getVariationKey()}\n"; // 'variation_express_checkout' // Force decision for specific rule within flag $contextWithRule = new OptimizelyDecisionContext('checkout_flow', 'experiment_rule_1'); $forcedDecisionForRule = new OptimizelyForcedDecision('variation_standard_checkout'); $userContext->setForcedDecision($contextWithRule, $forcedDecisionForRule); // Get forced decision $retrievedVariation = $userContext->getForcedDecision($context); echo "Retrieved forced variation: {$retrievedVariation}\n"; // Remove forced decision $userContext->removeForcedDecision($context); // Remove all forced decisions $userContext->removeAllForcedDecisions(); ?> ``` -------------------------------- ### Configure Optimizely Notification Listeners in PHP Source: https://context7.com/optimizely/php-sdk/llms.txt Subscribe to various SDK events such as decisions, track events, and configuration updates. Listeners can be added and removed using their notification ID. This allows for custom logging, analytics, or integrations by reacting to SDK activities. ```php featureKey}\n"; echo " Enabled: " . ($decisionInfo->featureEnabled ? 'true' : 'false') . "\n"; echo " Source: {$decisionInfo->source}\n"; } }; $notificationId = $optimizelyClient->notificationCenter->addNotificationListener( NotificationType::DECISION, $decisionCallback ); // Listen to track events $trackCallback = function($type, $userId, $attributes, $eventInfo) { echo "Event tracked:\n"; echo " Event: {$eventInfo->eventKey}\n"; echo " User: {$userId}\n"; if (isset($eventInfo->eventTags)) { echo " Tags: " . json_encode($eventInfo->eventTags) . "\n"; } }; $optimizelyClient->notificationCenter->addNotificationListener( NotificationType::TRACK, $trackCallback ); // Listen to config updates $configUpdateCallback = function() { echo "Datafile updated - new experiments/features available\n"; }; $optimizelyClient->notificationCenter->addNotificationListener( NotificationType::OPTIMIZELY_CONFIG_UPDATE, $configUpdateCallback ); // Remove listener by ID $optimizelyClient->notificationCenter->removeNotificationListener($notificationId); // Clear all listeners for a type $optimizelyClient->notificationCenter->clearNotificationListeners(NotificationType::DECISION); ?> ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.