### Expected output from running the PHP quickstart script Source: https://docs.optimizely.com/feature-experimentation/docs/php-quickstart Example output from the PHP quickstart script, showing flag variations, purchase prompts, and recorded results. ```text Flag on. User number 1496 saw flag variation: on and got products sorted by: popular_first config variable as part of flag rule: experiment_1 Pretend that user 1496 made a purchase? y/n n Optimizely didn't record a purchase in experiment results for user 1496 Flag off. User number 1194 saw flag variation: off and got products sorted by: alphabetical config variable as part of flag rule: experiment_1 Pretend that user 1194 made a purchase? y/n y Optimizely recorded a purchase in experiment results for user 1194 Flag off. User number 5815 saw flag variation: off and got products sorted by: alphabetical config variable as part of flag rule: experiment_1 Pretend that user 5815 made a purchase? y/n y Optimizely recorded a purchase in experiment results for user 5815 Flag on. User number 1248 saw flag variation: on and got products sorted by: popular_first config variable as part of flag rule: experiment_1 Pretend that user 1248 made a purchase? y/n y Optimizely recorded a purchase in experiment results for user 1248 Flag off. User number 9580 saw flag variation: off and got products sorted by: alphabetical config variable as part of flag rule: experiment_1 Pretend that user 9580 made a purchase? y/n n Optimizely didn't record a purchase in experiment results for user 9580 Done with your mocked A/B test. Check out your report at https://app.optimizely.com/v2/projects//reports Be sure to select the environment that corresponds to your SDK key ``` -------------------------------- ### Complete Example with Real-Time Audiences and event batching: v6 (After) Source: https://docs.optimizely.com/feature-experimentation/docs/upgrade-the-javascript-sdk-from-v5-to-v6 In v6, separate managers are created for project config, event batching, ODP, and logging, then passed to createInstance. This example shows the new modular setup. ```javascript import { createInstance, createPollingProjectConfigManager, createBatchEventProcessor, createOdpManager, createLogger, DEBUG, NOTIFICATION_TYPES } from '@optimizely/optimizely-sdk'; const projectConfigManager = createPollingProjectConfigManager({ sdkKey: '', autoUpdate: true, updateInterval: 60000 // 1 minute }); const batchEventProcessor = createBatchEventProcessor({ batchSize: 3, flushInterval: 10000, // 10 seconds }); const odpManager = createOdpManager({ segmentsCacheSize: 10, segmentsCacheTimeout: 60000 // 1 minute }); const logger = createLogger({ level: DEBUG }); const optimizely = createInstance({ projectConfigManager, eventProcessor: batchEventProcessor, odpManager, logger }); optimizely.notificationCenter.addNotificationListener( NOTIFICATION_TYPES.TRACK, (payload) => { console.log("Track event", payload); } ); ``` -------------------------------- ### Install the Go SDK with go get Source: https://docs.optimizely.com/feature-experimentation/docs/install-sdk-go Installs the Optimizely Go SDK. For version 2, use the commented alternative. ```go go get github.com/optimizely/go-sdk // for v2: go get github.com/optimizely/go-sdk/v2 ``` -------------------------------- ### Basic example v3 (Before) - useDecision Source: https://docs.optimizely.com/feature-experimentation/docs/upgrade-the-react-sdk-from-v3-to-v4 Shows the v3 SDK usage with createInstance, OptimizelyProvider, and useDecision. Use this as the starting point before migrating to v4. ```javascript import { createInstance, OptimizelyProvider, useDecision } from '@optimizely/react-sdk'; const optimizely = createInstance({ sdkKey: '' }); function Feature() { const [decision] = useDecision('flag-key'); return decision.enabled ? : ; } ``` -------------------------------- ### Complete example with event tracking and ODP - v3 (Before) Source: https://docs.optimizely.com/feature-experimentation/docs/upgrade-the-react-sdk-from-v3-to-v4 Shows the v3 SDK usage with event tracking and ODP options. Use this as the starting point for migrating a complete feature with tracking. ```javascript import { createInstance, OptimizelyProvider, useDecision, useTrackEvent } from '@optimizely/react-sdk'; const optimizely = createInstance({ sdkKey: '', eventBatchSize: 3, eventFlushInterval: 10000, odpOptions: { segmentsCacheSize: 10 }, }); function Feature() { const [decision] = useDecision('flag-key', { autoUpdate: true }); const [track] = useTrackEvent(); return (
{decision.enabled && }
); } ``` -------------------------------- ### Basic example with SDK key: v5 (Before) - createInstance with sdkKey Source: https://docs.optimizely.com/feature-experimentation/docs/upgrade-the-javascript-sdk-from-v5-to-v6 In v5, you could create an instance directly with the sdkKey option. This example shows the old way of initializing and checking readiness. ```javascript import { createInstance } from '@optimizely/optimizely-sdk'; const optimizely = createInstance({ sdkKey: '' }); optimizely.onReady().then(({ success }) => { if (success) { // Use the client } }); ``` -------------------------------- ### C# Quickstart Program.cs Source: https://docs.optimizely.com/feature-experimentation/docs/c-sharp-quickstart This is the complete sample code for the Optimizely C# quickstart. It initializes the Optimizely client synchronously, creates user contexts, makes decisions on the 'product_sort' flag, and retrieves the 'sort_method' variable. It also includes error handling and a final message if the flag is off for all users. Replace 'YOUR_SDK_KEY' with your actual SDK key before running. ```csharp using OptimizelySDK; namespace App; public static class Program { public static void Main() { // This Optimizely initialization is synchronous. For other methods, see the C# SDK reference. var optimizelyClient = OptimizelyFactory.NewDefaultInstance("YOUR_SDK_KEY"); if (!optimizelyClient.IsValid) { Console.WriteLine( "Optimizely client invalid. " + "Verify in Settings>Environments that you used the primary environment's SDK key"); optimizelyClient.Dispose(); return; } var hasOnFlags = false; /* * To get rapid demo results, generate random users. * Each user always sees the same variation unless you reconfigure the flag rule. */ var rnd = new Random(); for (var i = 0; i < 10; i++) { var userId = rnd.Next(1000, 9999).ToString(); // Create a user context to bucket the user into a variation. var user = optimizelyClient.CreateUserContext(userId); // "product_sort" corresponds to a flag key in your Optimizely project var decision = user.Decide("product_sort"); // Did decision fail with a critical error? if (string.IsNullOrEmpty(decision.VariationKey)) { Console.WriteLine(Environment.NewLine + Environment.NewLine + "Decision error: " + string.Join(" ", decision.Reasons)); continue; } /* * Get a dynamic configuration variable. * "sort_method" corresponds to a variable key in your Optimizely project. */ var sortMethod = decision.Variables.ToDictionary()["sort_method"]; hasOnFlags = hasOnFlags || decision.Enabled; /* * Mock what the user sees with print statements (in production, use flag variables to implement feature configuration) */ // always returns false until you enable a flag rule in your Optimizely project Console.WriteLine(Environment.NewLine + $"Flag {(decision.Enabled ? "on" : "off")}. " + $"User number {user.GetUserId()} saw " + $"flag variation {decision.VariationKey} and got " + $"products sorted by {sortMethod} config variable as part of " + $"flag rule {decision.RuleKey}"); } if (!hasOnFlags) { var projectId = optimizelyClient.ProjectConfigManager.GetConfig().ProjectId; var projectSettingsUrl = $"https://app.optimizely.com/v2/projects/{projectId}/settings/implementation"; Console.WriteLine(Environment.NewLine + Environment.NewLine + "Flag was off for everyone. Some reasons could include:" + Environment.NewLine + "1. Your sample size of users was too small. Re-run, or increase the iterations in the FOR loop" + Environment.NewLine + "2. By default you have 2 keys for 2 project environments (dev/prod). Verify in Settings>Environments that you used the right key for the environment where your flag is toggled to ON." + Environment.NewLine + Environment.NewLine + $"Check your key at {projectSettingsUrl}"); } optimizelyClient.Dispose(); } } ``` -------------------------------- ### Run Go quickstart and view A/B test output Source: https://docs.optimizely.com/feature-experimentation/docs/go-quickstart Run the Go quickstart program to execute the mocked A/B test. The output shows flag variations, user prompts, and whether Optimizely recorded a purchase for each user, ending with a link to the experiment report. ```shell go run optimizely-go-quickstart.go ``` ```text Flag on. User number 1496 saw flag variation: on and got products sorted by: popular_first config variable as part of flag rule: experiment_1 Pretend that user 1496 made a purchase? y/n n Optimizely didn't record a purchase in experiment results for user 1496 Flag off. User number 1194 saw flag variation: off and got products sorted by: alphabetical config variable as part of flag rule: experiment_1 Pretend that user 1194 made a purchase? y/n y Optimizely recorded a purchase in experiment results for user 1194 Flag off. User number 5815 saw flag variation: off and got products sorted by: alphabetical config variable as part of flag rule: experiment_1 Pretend that user 5815 made a purchase? y/n y Optimizely recorded a purchase in experiment results for user 5815 Flag on. User number 1248 saw flag variation: on and got products sorted by: popular_first config variable as part of flag rule: experiment_1 Pretend that user 1248 made a purchase? y/n y Optimizely recorded a purchase in experiment results for user 1248 Flag off. User number 9580 saw flag variation: off and got products sorted by: alphabetical config variable as part of flag rule: experiment_1 Pretend that user 9580 made a purchase? y/n n Optimizely didn't record a purchase in experiment results for user 9580 Done with your mocked A/B test. Check out your report at https://app.optimizely.com/v2/projects//reports Be sure to select the environment that corresponds to your SDK key ``` -------------------------------- ### C# migration example from legacy to new Decision and Event Tracking APIs Source: https://docs.optimizely.com/feature-experimentation/docs/migrate-from-older-versions-csharp Use this example to migrate from legacy Full Stack methods to the new Decision and Event Tracking APIs. It shows the old and new approaches for feature enabled checks, activate/get variation, get all feature variables, get enabled features, and tracking events. The example requires creating a user context with attributes first. ```csharp using OptimizelySDK; using OptimizelySDK.Entity; using OptimizelySDK.OptimizelyDecisions; /* * Prerequisites for new methods: create a user */ var optimizely = OptimizelyFactory.NewDefaultInstance("YOUR_SDK_KEY"); var attributes = new UserAttributes { { "is_logged_in", true } }; var user = optimizely.CreateUserContext("user_123", attributes); /* * Is Feature Enabled */ // old method bool enabled = optimizely.IsFeatureEnabled("flag_1", "user_123", attributes); // new method var decision = user.Decide("flag_1"); bool enabled = decision.Enabled; /* * Activate & Get Variation */ // old method var variation = optimizely.Activate("experiment_1", "user_123", attributes); // new method var variationKey = decision.VariationKey; /* * Get All Feature Variables */ // old method var json = optimizely.GetAllFeatureVariables("flag_1", "user_123", attributes); // new method var json = decision.Variables; /* * Get Enabled Features */ // old method var enabledFlags = optimizely.GetEnabledFeatures("user_123", attributes); // new method var options = new[] { OptimizelyDecideOption.ENABLED_FLAGS_ONLY }; var decisions = user.DecideAll(options); var enabledFlags = decisions.Keys; /* * Track */ // old method var tags = new EventTags { { "revenue", 42 } }; tags.Add("purchase_count", 2); optimizely.Track("my_purchase_event_key", "user_123", attributes, tags); // new method user.TrackEvent("my_purchase_event_key", tags); ``` -------------------------------- ### Swift: Image carousel with Optimizely flag and variables Source: https://docs.optimizely.com/feature-experimentation/docs/flag-variable-example-with-an-image-carousel Swift code for an image carousel that uses the Optimizely Feature Experimentation SDK. It initializes the client with a placeholder SDK key, starts it, and on success decides the variation for a user. It checks if the flag is enabled, retrieves all variable values, and gets the 'numberOfSlides' variable. Requires installing the Swift SDK and replacing '' with a real SDK key. ```swift import UIKit // Import the Optimizely iOS SDK for Feature Experimentation import Optimizely class ViewController: UIViewController { // MARK: - Properties // Replace this with the real OptimizelyClient initialization let optimizelyClient = OptimizelyClient(sdkKey: "") // Example: A simple model for each slide in the carousel struct CarouselSlide { let backgroundImageUrl: String let marketingTagline: String let buttonText: String let buttonColor: String let buttonClickUrl: String let backgroundClickUrl: String let buttonWidth: Int let buttonHeight: Int } var slides: [CarouselSlide] = [] // MARK: - View Lifecycle override func viewDidLoad() { super.viewDidLoad() // Start the Optimizely client to fetch the datafile optimizelyClient.start { [weak self] result in switch result { case .failure(let error): print("Error starting Optimizely Client: \(error)") // Fallback logic could go here case .success: // Successfully started the client, now decide which variation this user sees self?.configureCarousel() } } } // MARK: - Carousel Configuration func configureCarousel() { // The flag key as defined in your Optimizely project let flagKey = "image_carousel_flag" // This is a unique user ID. In production, use something that identifies the user let user = optimizelyClient.createUserContext(userId: "user123") // Decide which variation the user sees. // Note: The actual method or function name may vary depending on the Swift SDK version let decision = user.decide(key: flagKey) // Check if the flag is enabled; if not, use fallback or default logic guard decision.enabled == true else { print("Flag '\(flagKey)' is not enabled. Using default configuration.") return } // all variable values let allVarValues: OptimizelyJSON = decision.variables print(allVarValues) // Retrieve the variable values from the decision object. // Depending on the SDK version, you might access them differently: // 1. Integer variable for numberOfSlides let numberOfSlides: Int? = decision.variables.getValue(jsonPath: "numberOfSlides") // Initialize an array to store slides var tempSlides: [CarouselSlide] = [] ``` -------------------------------- ### start Source: https://docs.optimizely.com/feature-experimentation/docs/initialize-sdk-swift Initializes the Swift SDK with the provided configuration parameters. ```APIDOC ## [start] start ### Description Initializes the Swift SDK and instantiates an instance of the Optimizely client class that exposes API methods like the Decide methods. Each client corresponds to the datafile representing the state of a project for a certain environment. ### Method start ### Parameters - **sdkKey** (String) - Required - SDK Key. - **logger** (OPTLogger) - Optional - A custom logger. - **eventDispatcher** (OPTEventDispatcher) - Optional - A custom event handler. - **userProfileService** (OTPUserProfileService) - Optional - A custom user profile service. - **odpManager** (OdpManager) - Optional - A custom Optimizely Data Platform (ODP) manager. You must configure this parameter to use Real-Time Audiences for Feature Experimentation. - **periodicDownloadInterval** (Int) - Optional - A custom interval for periodic background datafile download in seconds (default = 10 * 60 secs). ``` -------------------------------- ### PHP SDK quickstart sample code Source: https://docs.optimizely.com/feature-experimentation/docs/php-quickstart Copy this code into optimizely-php-quickstart.php. Replace YOUR_SDK_KEY with your primary environment's SDK key. The code creates a client, generates random users, and makes decisions on the 'product_sort' flag, printing results. It also checks for client validity and flag enablement. ```php isValid()) { /* * To get rapid demo results, generate random users. Each user always sees the same variation unless you reconfigure the flag rule. */ mt_srand(); $hasOnFlags = false; for ($i = 0; $i < 10; $i++) { $userId = strval(mt_rand(1000, 9999)); // Create hardcoded user & bucket user into a flag variation $user = $optimizelyClient->createUserContext($userId); // "product_sort" corresponds to a flag key in your Optimizely project $decision = $user->decide('product_sort'); // Did decision fail with a critical error? if (empty($decision->getVariationKey())) { printf("decision error: %s", implode(', ', $decision->getReasons())); } /* * Get a dynamic configuration variable * "sort_method" corresponds to a variable key in your Optimizely project */ $sortMethod = $decision->getVariables() ['sort_method']; /* * Mock what the user sees with print statements (in production, use flag variables to implement feature configuration) */ // Always returns false until you enable a flag rule in your Optimizely project $enabled = $decision->getEnabled(); if ($enabled) { $hasOnFlags = true; } printf("\n\nFlag %s. User number %s saw flag variation %s and got products sorted by %s config variable as part of flag rule: %s", $enabled ? "on" : "off", $user->getUserId(), $decision->getVariationKey(), $sortMethod, $decision->getRuleKey()); } if (!$hasOnFlags) { printf("\n\n Flag was off for everyone. Some reasons could include: \n Your sample size of users was too small. Rerun, or increase the iterations in the FOR loop \n Check your SDK key. Verify in Settings>Environments that you used the right key for the environment where your flag is toggled to ON. \ncheck your key at https://app.optimizely.com/v2/projects/%s/settings/implementation", $optimizelyClient ->configManager ->getConfig() ->getProjectId()); } } else { printf("Optimizely client invalid. Verify in Settings>Environments that you used the primary environment's SDK key"); } ``` -------------------------------- ### Swift: Set, get, and remove forced decisions with Optimizely Source: https://docs.optimizely.com/feature-experimentation/docs/forced-decision-methods-swift Use this Swift example to manage forced decisions in Optimizely Feature Experimentation. It shows how to set forced decisions for a flag, an A/B test rule, and a delivery rule, then how to get and remove them. The example assumes you have already initialized the Optimizely client with a datafile and created a user context with attributes. ```swift let optimizely = OptimizelyClient(sdkKey: “sdk-key”) optimizely.start(datafile: datafile) let user = optimizely.createUserContext(userId: “test-user”, attributes: attributes) let flagContext = OptimizelyDecisionContext(flagKey: "flag-1") let flagAndABTestContext = OptimizelyDecisionContext(flagKey: "flag-1", ruleKey: "ab-test-1") let flagAndDeliveryRuleContext = OptimizelyDecisionContext(flagKey: "flag-1", ruleKey: "delivery-1") let variationAForcedDecision = OptimizelyForcedDecision(variationKey: "variation-a") let variationBForcedDecision = OptimizelyForcedDecision(variationKey: "variation-b") let variationOnForcedDecision = OptimizelyForcedDecision(variationKey: "on") // set a forced decision for a flag var success = user.setForcedDecision(context: flagContext, decision: variationAForcedDecision) decision = user.decide(key: "flag-1") // set a forced decision for an ab-test rule success = user.setForcedDecision(context: flagAndABTestContext, decision: variationBForcedDecision) decision = user.decide(key: "flag-1") // set a forced variation for a delivery rule success = user.setForcedDecision(context: flagAndDeliveryRuleContext, decision: variationOnForcedDecision) decision = user.decide(key: "flag-1") // get forced variations let forcedDecision = user.getForcedDecision(context: flagContext) print("[ForcedDecision] variationKey = \(forcedDecision!.variationKey)") // remove forced variations success = user.removeForcedDecision(context: flagAndABTestContext) success = user.removeAllForcedDecisions() ``` -------------------------------- ### useDecision hook example in React Source: https://docs.optimizely.com/feature-experimentation/docs/usedecision-react-prior-to-v4 Example of using the useDecision hook from @optimizely/react-sdk to get a decision for a flag and update the UI based on the decision. The hook returns an array with the decision object and a clientReady boolean. The example shows how to use the decision's enabled and variationKey properties. ```javascript import { useEffect } from 'react'; import { useDecision } from '@optimizely/react-sdk'; function LoginComponent() { const [decision, clientReady] = useDecision( 'flag1', { autoUpdate: true }, { /* (Optional) User overrides */ } ); useEffect(() => { document.title = decision.enabled ? 'New Feature flag' : 'Old Feature flag'; }, [decision]); return (

Click to login

); } ``` -------------------------------- ### Complete Example with Real-Time Audiences and event batching: v5 (Before) Source: https://docs.optimizely.com/feature-experimentation/docs/upgrade-the-javascript-sdk-from-v5-to-v6 In v5, all configuration options (datafileOptions, eventBatchSize, eventFlushInterval, logLevel, odpOptions) were passed directly to createInstance. This example shows the old way of setting up auto-update, batching, logging, and ODP segments. ```javascript import { createInstance, LogLevel } from '@optimizely/optimizely-sdk'; const optimizely = createInstance({ sdkKey: '', datafileOptions: { autoUpdate: true, updateInterval: 60000 // 1 minute }, eventBatchSize: 3, eventFlushInterval: 10000, // 10 seconds logLevel: LogLevel.DEBUG, odpOptions: { segmentsCacheSize: 10, segmentsCacheTimeout: 60000 // 1 minute } }); optimizely.notificationCenter.addNotificationListener( enums.NOTIFICATION_TYPES.TRACK, (payload) => { console.log("Track event", payload); } ); ``` -------------------------------- ### useOptimizelyClient hook example Source: https://docs.optimizely.com/feature-experimentation/docs/useoptimizely-client-for-the-react-native-sdk Use this hook inside a component wrapped by OptimizelyProvider to get the client instance. The example checks if the client exists, creates a user context, and makes a decision for a flag key. ```javascript import { Text, TouchableOpacity } from 'react-native'; import { useOptimizelyClient } from '@optimizely/react-sdk'; function MyComponent() { const client = useOptimizelyClient(); const handlePress = () => { if (client) { const user = client.createUserContext('user-123', { plan: 'gold' }); const decision = user.decide('flag-key'); console.log('Decision:', decision); } }; return ( Check Flag ); } ``` -------------------------------- ### Optimizely Go SDK quickstart sample app Source: https://docs.optimizely.com/feature-experimentation/docs/go-quickstart Sample Go app that initializes the Optimizely client, creates a user context, and makes a decision for the 'product_sort' flag. Replace 'YOUR_SDK_KEY' with your actual SDK key. The app prints decision results and troubleshooting hints if the flag is off. ```go // Package main // package main import ( "fmt" "math/rand" "time" optly "github.com/optimizely/go-sdk/v2" "github.com/optimizely/go-sdk/v2/pkg/logging" ) func main() { logging.SetLogLevel(logging.LogLevelError) // this Optimizely initialization is synchronous. for other methods see the Go SDK reference if optimizelyClient, err := optly.Client("YOUR_SDK_KEY"); err == nil { // -------------------------------- // to get rapid demo results, generate random users. Each user always sees the same variation unless you reconfigure the flag rule. // -------------------------------- rand.Seed(time.Now().UnixNano()) flagsStatus := "off" for i := 0; i < 10; i++ { userID := fmt.Sprintf("%v", rand.Intn(8999)+1000) // -------------------------------- // Create hardcoded user & bucket user into a flag variation // -------------------------------- user := optimizelyClient.CreateUserContext(userID, nil) // "product_sort" corresponds to a flag key in your Optimizely project decision := user.Decide("product_sort", nil) // did decision fail with a critical error? if decision.VariationKey == "" { fmt.Printf("\ndecision error: %q", decision.Reasons) } // get a dynamic configuration variable // "sort_method" corresponds to a variable key in your Optimizely project sortMethod := decision.Variables.ToMap()["sort_method"] // -------------------------------- // Mock what the user sees with print statements (in production, use flag variables to implement feature configuration) // -------------------------------- // always returns false until you enable a flag rule in your Optimizely project if decision.Enabled { // Keep count how many users had the flag enabled flagsStatus = "on" } fmt.Printf("\n\nFlag %s. User number %v saw flag variation: %s and got products sorted by: %v config variable as part of flag rule: %s", flagsStatus, user.GetUserID(), decision.VariationKey, sortMethod, decision.RuleKey) } if flagsStatus == "off" { fmt.Println("Flag was off for everyone. Some reasons could include:") fmt.Println("1. Your sample size of users was too small. Rerun, or increase the iterations in the FOR loop") fmt.Println("2. Check your SDK key. Verify in Settings>Environments that you used the right key for the environment where your flag is toggled to ON.") if config, err := optimizelyClient.ConfigManager.GetConfig(); err == nil { fmt.Printf("\ncheck your key at https://app.optimizely.com/v2/projects/%s/settings/implementation", config.GetProjectID()) } } } else { fmt.Println("Optimizely client invalid. Verify in Settings>Environments that you used the primary environment's SDK key") } } ``` -------------------------------- ### useDecide hook example in React Native Source: https://docs.optimizely.com/feature-experimentation/docs/decide-hooks-for-the-react-native-sdk Example of using the useDecide hook to get a decision for the 'product_sort' flag, including loading and error states, and accessing decision properties. Requires @optimizely/react-sdk and react-native. ```javascript import { View } from 'react-native'; import { useDecide, OptimizelyDecideOption } from '@optimizely/react-sdk'; function MyComponent() { const { decision, isLoading, error } = useDecide('product_sort', { decideOptions: [OptimizelyDecideOption.INCLUDE_REASONS], }); if (isLoading) return ; if (error) return ; const variationKey = decision.variationKey; const enabled = decision.enabled; const sortMethod = decision.variables['sort_method']; return {enabled ? : }; } ``` -------------------------------- ### Java: Set and get forced decisions Source: https://docs.optimizely.com/feature-experimentation/docs/use-forced-bucketing Java example showing how to create a user context, set forced decisions for a flag, an A/B test rule, and a delivery rule, then get and remove forced decisions. ```java /* Create the OptimizelyUserContext, passing in the UserId and Attributes */ OptimizelyUserContext user = optimizelyClient.createUserContext("user-id"); OptimizelyDecisionContext flagContext = new OptimizelyDecisionContext("flag-1", null); OptimizelyDecisionContext flagAndABTestContext = new OptimizelyDecisionContext("flag-1", "exp-1"); OptimizelyDecisionContext flagAndDeliveryRuleContext = new OptimizelyDecisionContext("flag-1", "delivery-1"); OptimizelyForcedDecision variationAForcedDecision = new OptimizelyForcedDecision("variation-a"); OptimizelyForcedDecision variationBForcedDecision = new OptimizelyForcedDecision("variation-b"); OptimizelyForcedDecision variationOnForcedDecision = new OptimizelyForcedDecision("on"); // set a forced decision for a flag Boolean success = user.setForcedDecision(flagContext, variationAForcedDecision); OptimizelyDecision decision = user.decide("flag-1"); // set a forced decision for an ab-test rule success = user.setForcedDecision(flagAndABTestContext, variationBForcedDecision); decision = user.decide("flag-1"); // set a forced variation for a delivery rule success = user.setForcedDecision(flagAndDeliveryRuleContext, variationOnForcedDecision); decision = user.decide("flag-1"); // get forced variations OptimizelyForcedDecision forcedDecision = user.getForcedDecision(flagContext); System.out.println("[ForcedDecision] variationKey = " + forcedDecision.getVariationKey()); // remove forced variations success = user.removeForcedDecision(flagAndABTestContext); success = user.removeAllForcedDecisions(); ``` -------------------------------- ### Install the Go SDK from CLI source Source: https://docs.optimizely.com/feature-experimentation/docs/install-sdk-go Installs the Go SDK from the CLI source by fetching, navigating to the source directory, and running go install. ```go go get github.com/optimizely/go-sdk // for v2: go get github.com/optimizely/go-sdk/v2 cd $GOPATH/src/github.com/optimizely/go-sdk go install ``` -------------------------------- ### Kotlin: Set and get forced decisions Source: https://docs.optimizely.com/feature-experimentation/docs/use-forced-bucketing Kotlin example showing how to create a user context, set forced decisions for a flag, an A/B test rule, and a delivery rule, then get and remove forced decisions. ```kotlin // Create the OptimizelyUserContext, passing in the UserId and Attributes val user = optimizelyClient.createUserContext("user-id") val flagContext = OptimizelyDecisionContext("flag-1", null) val flagAndABTestContext = OptimizelyDecisionContext("flag-1", "exp-1") val flagAndDeliveryRuleContext = OptimizelyDecisionContext("flag-1", "delivery-1") val variationAForcedDecision = OptimizelyForcedDecision("variation-a") val variationBForcedDecision = OptimizelyForcedDecision("variation-b") val variationOnForcedDecision = OptimizelyForcedDecision("on") // set a forced decision for a flag var success = user!!.setForcedDecision(flagContext, variationAForcedDecision) var decision = user.decide("flag-1") // set a forced decision for an ab-test rule success = user.setForcedDecision(flagAndABTestContext, variationBForcedDecision) decision = user.decide("flag-1") // set a forced variation for a delivery rule success = user.setForcedDecision(flagAndDeliveryRuleContext, variationOnForcedDecision) decision = user.decide("flag-1") // get forced variations val forcedDecision = user.getForcedDecision(flagContext) println("[ForcedDecision] variationKey = " + forcedDecision!!.variationKey) // remove forced variations success = user.removeForcedDecision(flagAndABTestContext) success = user.removeAllForcedDecisions() ``` -------------------------------- ### Create local environment file Source: https://docs.optimizely.com/feature-experimentation/docs/vercel-functions Create a local environment file from the example and add your SDK key. ```shell cp .env.example .env.local ``` -------------------------------- ### Run the PHP sample app with php optimizely-php-quickstart.php Source: https://docs.optimizely.com/feature-experimentation/docs/php-quickstart Run the PHP sample app. Output displays flag decisions for simulated users, showing whether each user's flag is on or off, and which sort_method variable value and flag rule were used. ```shell php optimizely-php-quickstart.php ``` -------------------------------- ### Set, Get, and Remove Forced Decisions in Go Source: https://docs.optimizely.com/feature-experimentation/docs/forced-decision-methods-go This example demonstrates how to use the Optimizely Go SDK to set forced decisions for a flag, an A/B test rule, and a delivery rule, then get and remove them. It uses the OptimizelyFactory to create a client, CreateUserContext to create a user, and SetForcedDecision, GetForcedDecision, RemoveForcedDecision, and RemoveAllForcedDecisions methods. The example shows how to check for errors and print the forced variation key. ```go factory := &client.OptimizelyFactory{SDKKey: "sdk-key"} if optimizely, err := factory.StaticClient(); err == nil { user := optimizely.CreateUserContext("test-user", map[string]interface{}{}) flagContext := decision.OptimizelyDecisionContext{FlagKey: "flag-1"} flagAndABTestContext := decision.OptimizelyDecisionContext{FlagKey: "flag-1", RuleKey: "ab-test-1"} flagAndDeliveryRuleContext := decision.OptimizelyDecisionContext{FlagKey: "flag-1", RuleKey: "delivery-1"} variationAForcedDecision := decision.OptimizelyForcedDecision{VariationKey: "variation-a"} variationBForcedDecision := decision.OptimizelyForcedDecision{VariationKey: "variation-b"} variationOnForcedDecision := decision.OptimizelyForcedDecision{VariationKey: "on"} // set a forced decision for a flag success := user.SetForcedDecision(flagContext, variationAForcedDecision) decision := user.Decide("flag-1", nil) // set a forced decision for an ab-test rule success = user.SetForcedDecision(flagAndABTestContext, variationBForcedDecision) decision = user.Decide("flag-1", nil) // set a forced variation for a delivery rule success = user.SetForcedDecision(flagAndDeliveryRuleContext, variationOnForcedDecision) decision = user.Decide("flag-1", nil) // get forced variations if forcedDecision, err := user.GetForcedDecision(flagContext); err == nil { fmt.Println("[ForcedDecision] variationKey = " + forcedDecision.VariationKey) } // remove forced variations success = user.RemoveForcedDecision(flagAndABTestContext) success = user.RemoveAllForcedDecisions() } ``` -------------------------------- ### Initialize OptimizelyClient and make a decision in Swift Source: https://docs.optimizely.com/feature-experimentation/docs/initialize-sdk-swift Shows how to create an OptimizelyClient with an SDK key, create a user context, and start the client synchronously or asynchronously. The synchronous path uses `start(datafile:)` and the asynchronous path uses `start` with a completion callback. Both paths then call `user.decide(key:)` to get a decision for a flag rule. ```swift // Build and config OptimizelyClient optimizely = OptimizelyClient(sdkKey: "YOUR_SDK_KEY") let user = optimizely.createUserContext(userId: userId) // Synchronously initialize the client, then make a decision for a flag rule (such as an A/B test) do { try optimizely.start(datafile: datafileJSON) let decision = user.decide(key: "flagKey") let variationKey = decision.variationKey } catch { // errors } // Or, instantiate it asynchronously with a callback optimizely.start { result in let decision = user.decide(key: "flagKey") let variationKey = decision.variationKey } ```