HomeGuidesAPI Reference
Submit Documentation FeedbackJoin Developer CommunityLog In

Example usage

This topic gives a brief code example of how to use the Optimizely PHP SDK to evaluate feature flags, activate A/B tests, or feature tests.

Once you've installed an SDK, import the Optimizely library into your code, get your Optimizely project's datafile, and instantiate a client. Then, you can use the client to evaluate flag rules, including A/B tests and flag deliveries.

This example demonstrates the basic usage of each of these concepts:
Evaluate a flag with the key product_sort using the Decide method. As a side effect, the Decide function also sends a decision event to Optimizely to record that the current user has been exposed to the experiment.

  1. Conditionally execute your feature code. You have a couple of options:
  • Based on flag enabled state, check a configuration variable on the flag called sort_method. The SDK evaluates your flag rules and determines what flag variation the user is in, and therefore which sort method they should see.
  • Based on the flag variation, run 'control' or 'treatment' code.
  1. Use event tracking to track an event called purchased. This conversion event measures the impact of an experiment. Using the Track Event method, the purchase is automatically attributed back to the running A/B test for which we made a decision, and the SDK sends a network request to Optimizely via the customizable event dispatcher so we can count it in your Results page.
use Optimizely\Optimizely;

// Instantiate an Optimizely client
$sdkKey = "<Your_SDK_Key>";
$optimizelyClient = OptimizelyFactory::createDefaultInstance($sdkKey);

$user = $optimizelyClient->createUserContext('user123', ['logged_in' => true]);

$decision = $user->decide('product_sort');

$variation = $decision->getVariationKey();
if ($variation == null) {
  $reasons = $decision->getReasons();
  $reasons = json_encode($reasons);
  echo "[decide] error: {$reasons}";
}
// execute code based on flag variable 
$enabled = $decision->getEnabled();

if ($enabled) {
  $sort_method = (string) $decision->getVariables()['sort_method'];
}

// or execute code based on flag variation:
if ($variation == 'control') {
  // Execute code for variation A
} else if ($variation == 'treatment') {
  // Execute code for variation B
} else {
  // Execute code for users who don't qualify for the experiment
}

// Track an event
$user->trackEvent('purchased');

Did this page help you?