이 페이지에서

For AI agents: a documentation index is available at /docs/llms.txt. Append .md to any page URL for markdown, or send Accept: text/markdown.

실험 PHP SDK

Amplitude Experiment의 서버 측 PHP SDK 구현에 대한 공식 문서입니다.

설치

PHP 버전 호환성

PHP Server SDK는 PHP 7.4 이상에서 작동합니다.

Composer를 사용하여 PHP Server SDK를 설치합니다.

bash
composer require amplitude/experiment-php-server

원격 평가

SDK는 사용자를 위한 변형을 가져오기 위해 원격 평가를 지원하고 사용합니다.

빠른 시작

  1. 실험 클라이언트 초기화
  2. 사용자를 위한 변형 가져오기
  3. 플래그 변형에 액세스
php
<?php
// (1) Initialize the experiment client
$experiment = new \AmplitudeExperiment\Experiment();
$client = $experiment->initializeRemote('<DEPLOYMENT_KEY>');
// (2) Fetch variants for a user
$user = \AmplitudeExperiment\User::builder()
    ->deviceId('abcdefg')
    ->userId('user@company.com')
    ->userProperties(['premium' => true])
    ->build();
$variants = $client->fetch($user);
// (3) Access a flag's variant
$variant = $variants['FLAG_KEY'] ?? null;
if ($variant) {
    if ($variant->value == 'on') {
        // Flag is on
    } else {
        // Flag is off
    }
}

원격 평가 초기화

서버 시작 시 초기화되도록 SDK를 구성합니다.apiKey 매개변수에 전달하는 배포 키 인수는 분석 이벤트를 전송하는 동일한 프로젝트 내에 있어야 합니다.

php
<?php
initializeRemote(string $apiKey, ?RemoteEvaluationConfig $config = null): RemoteEvaluationClient

구성

초기화 시 SDK 클라이언트를 구성할 수 있습니다.

EU 데이터 센터

Amplitude의 EU 데이터 센터를 사용하는 경우, 초기화 시 serverUrl 옵션을 https://api.lab.eu.amplitude.com
으로 설정하십시오.

가져오기

사용자의 변형을 가져오고 결과를 반환합니다. 원격으로 평가 함수는 SDK 클라이언트를 초기화하는 데 사용된 배포와 관련된 플래그에 대해 사용자를 평가합니다.

php
<?php
fetch(User $user, ?FetchOptions $fetchOptions = null): array<Variant>
// An array of variants is returned on success, an empty array is returned on failure

FetchOptions

php
<?php
$user = \AmplitudeExperiment\User::builder()
    ->deviceId('abcdefg')
    ->userId('user@company.com')
    ->userProperties(['premium' => true])
    ->build();
$variants = $client->fetch($user);

사용자의 변형을 가져온 후에는 특정 플래그의 변형에 액세스하고 싶을 수 있습니다.

php
<?php
$variant = $variants['FLAG-KEY'] ?? null;
if ($variant) {
    if ($variant->value == 'on') {
        // Flag is on
    } else {
        // Flag is off
    }
}

지역 평가

로컬 평가를 통해 사용자를 위한 변형 평가를 구현합니다. 로컬 평가를 사용하려는 경우 트레이드오프를 이해해야 합니다.

빠른 시작

  1. 로컬 평가 클라이언트를 초기화합니다.
  2. 로컬 평가 클라이언트의 플래그 구성을 가져옵니다.
  3. 사용자를 평가합니다.
php
<?php
// (1) Initialize the experiment client
$experiment = new \AmplitudeExperiment\Experiment();
$client = $experiment->initializeLocal('<DEPLOYMENT_KEY>');
// (2) Fetch flags for the local evaluation client.
$client->refreshFlagConfigs();
// (3) Evaluate a user.
$user = \AmplitudeExperiment\User::builder()
    ->deviceId('abcdefg')
    ->userId('user@company.com')
    ->userProperties(['premium' => true])
    ->build();
$variants = $client->evaluate($user);

로컬 평가 초기화

로컬 평가를 참조하십시오.

서버 배포 키

로컬 평가 플래그 구성에 액세스하려면 서버 배포 키를 사용하여 로컬 평가 클라이언트를 초기화하십시오.

php
initializeLocal(string $apiKey, ?LocalEvaluationConfig $config = null): LocalEvaluationClient

구성

초기화 시 SDK 클라이언트를 구성할 수 있습니다.

EU 데이터 센터

Amplitude의 EU 데이터 센터를 사용하는 경우, 초기화 시 serverUrl 옵션을 https://api.lab.eu.amplitude.com로 구성하십시오.

refreshFlagConfigs

평가를 위해 최신 로컬 평가 모드 플래그 구성을 가져옵니다.

php
refreshFlagConfigs(): void

evaluate()를 사용하기 전에 플래그 구성이 최신 상태인지 확인하려면 refreshFlagConfigs()를 호출하십시오.

php
<?php
$client->refreshFlagConfigs();

getFlagConfigs

클라이언트에서 사용된 플래그 구성을 반환합니다.

php
getFlagConfigs(): array

반환된 플래그 구성을 사용하여 로컬 평가 클라이언트를 부트스트랩하여 시작 시간을 줄일 수 있습니다.

php
<?php
$client->getFlagConfigs();

평가

가져온 플래그를 기반으로 평가 로직을 실행합니다 refreshFlagConfigs(). 사용자 객체 evaluate() 인수를 지정합니다. 필요한 플래그 변형의 특정 하위 집합만 필요한 경우 선택적으로 플래그 키 배열을 전달합니다.

노출 추적

노출 추적을 활성화하려면 exposureConfig을 설정하십시오. 그런 다음 evaluate()을 호출할 때 EvaluateOptions의 tracksExposure을 true(으)로 설정하십시오.

php
evaluate(User $user, array $flagKeys = [], ?EvaluateOptions $options = null): array
php
<?php
// The user to evaluate
$user = \AmplitudeExperiment\User::builder()
        ->deviceId('abcdefg')
        ->build();
// Evaluate all flag variants
$allVariants = $client->evaluate($user);
// Evaluate a specific subset of flag variants
$specificVariants = $client->evaluate($user, [
  'my-local-flag-1',
  'my-local-flag-2',
]);
// Access a flag's variant
$variant = $allVariants['FLAG_KEY'] ?? null;
if ($variant) {
    if ($variant->value == 'on') {
        // Flag is on
    } else {
        // Flag is off
    }
}

평가 옵션

할당 추적

더 이상 사용되지 않습니다. 대신 노출 추적을 사용하십시오.

할당 이벤트를 Amplitude로 전송하도록 로컬 평가 클라이언트를 구성할 수 있습니다.

AssignmentTrackingProvider

로컬 평가 클라이언트는 할당 추적 공급자를 사용하여 할당 이벤트를 Amplitude로 전송합니다. Amplitude는 기본 할당 추적 공급자를 제공하지만 이는 동기식 특성 때문에 테스트에 가장 적합합니다. Amplitude는 유연성과 성능을 향상시키기 위해 사용자 지정 공급자를 사용할 것을 권장합니다.

php
<?php
interface AssignmentTrackingProvider {
  public function track(Assignment $assignment): void;
}

로컬 평가 클라이언트는 추적되지 않은 할당 이벤트가 있다고 판단할 때 호출합니다track(). evaluate()의 결과 할당을 할당 캐시와 비교하여 캐시에 없는 경우 이를 추적합니다.

DefaultAssignmentTrackingProvider

기본 할당 추적 공급자는 내부 Amplitude 패키지를 사용하여 동기식 HTTP 요청을 통해 할당 이벤트를 전송하는 인터페이스의 기본 구현입니다.

php
<?php
class DefaultAssignmentTrackingProvider implements AssignmentTrackingProvider {
  public function __construct(Amplitude $amplitude);
}

Amplitude

AmplitudeConfig

php
<?php
$config = \AmplitudeExperiment\Amplitude\AmplitudeConfig::builder()
          ->useBatch(true)
          ->minIdLength(10)
          ->build();
$amplitude = new \AmplitudeExperiment\Amplitude\Amplitude('<API_Key>', $config);
$defaultAssignmentTrackingProvider = new \AmplitudeExperiment\Assignment\DefaultAssignmentTrackingProvider($amplitude);

노출 추적

노출 이벤트를 Amplitude로 전송하도록 로컬 평가 클라이언트를 구성할 수 있습니다.

ExposureTrackingProvider

로컬 평가 클라이언트는 노출 추적 공급자를 사용하여 노출 이벤트를 전송합니다. Amplitude는 Amplitude로 이벤트를 추적하는 기본 노출 추적 제공자를 제공합니다. 사용자 지정 공급자를 구현하여 다른 대상으로의 이벤트를 추적하거나 추적 동작을 사용자 정의할 수 있습니다.

php
<?php
interface ExposureTrackingProvider {
  public function track(Exposure $exposure): void;
}

로컬 평가 클라이언트는 추적되지 않은 노출 이벤트가 있다고 판단할 때 호출합니다track(). 이는 evaluate()의 결과 노출을 노출 캐시와 비교하여 해당 노출이 캐시에 없을 경우 이를 추적합니다.

DefaultExposureTrackingProvider

기본 노출 추적 공급자는 동기식 HTTP 요청을 통해 내부 Amplitude 패키지를 사용하여 노출 이벤트를 Amplitude로 전송하는 ExposureTrackingProvider 인터페이스의 구현입니다.

php
<?php
class DefaultExposureTrackingProvider implements ExposureTrackingProvider {
  public function __construct(Amplitude $amplitude);
}

Amplitude

AmplitudeConfig

php
<?php
$config = \AmplitudeExperiment\Amplitude\AmplitudeConfig::builder()
          ->useBatch(true)
          ->minIdLength(10)
          ->build();
$amplitude = new \AmplitudeExperiment\Amplitude\Amplitude('<API_Key>', $config);
$defaultExposureTrackingProvider = new \AmplitudeExperiment\Exposure\DefaultExposureTrackingProvider($amplitude);

사용자 지정 로거

PSR 로거 인터페이스를 구현하는 사용자 지정 로거를 사용하도록 로컬 및 원격 평가 클라이언트를 구성합니다. 그렇지 않은 경우 SDK는 기본 error_log 기반 로거를 사용합니다.

로그 수준

SDK는 다음과 같은 로그 수준을 사용합니다.

사용자 지정 HTTP 클라이언트

로컬 및 원격 평가 클라이언트가 HTTPClientInterface를 구현하는 사용자 지정 HTTP 클라이언트를 사용하도록 구성합니다. 그렇지 않은 경우 SDK는 기본 Guzzle 기반 HTTP 클라이언트를 사용합니다.

HTTPClientInterface

GuzzleHTTPClient

RemoteEvaluationConfig 및 LocalEvaluationConfig의 guzzleClientConfig 옵션으로 기본 Guzzle 클라이언트를 구성합니다.

php
<?php
// Configure the default Guzzle client
$config = \AmplitudeExperiment\RemoteEvaluationConfig::builder()
          ->guzzleClientConfig(['timeoutMillis' => 5000, 'retries' => 10])
          ->build();

Amplitude 쿠키에 액세스

클라이언트 측에서 Amplitude 애널리틱스 SDK를 사용하는 경우, PHP 서버 SDK는 Amplitude ID 쿠키를 구문 분석하고 상호 작용할 수 있는 편리한 함수를 포함하는 AmplitudeCookie 클래스를 제공합니다. 이 클래스는 특히 클라이언트가 아직 장치 ID를 생성하지 않은 경우 서버의 장치 ID가 클라이언트에 설정된 장치 ID와 일치하도록 보장합니다.

php
<?php
use AmplitudeExperiment\AmplitudeCookie;
// Get the cookie name for the Amplitude API key
// For Browser SDK 2.0 cookies, use true as second parameter:
// $amp_cookie_name = AmplitudeCookie::cookieName('amplitude-api-key', true);
$amp_cookie_name = AmplitudeCookie::cookieName('amplitude-api-key');
$device_id = null;
// Try to get device ID from existing cookie
if (isset($_COOKIE[$amp_cookie_name])) {
  $cookie_data = AmplitudeCookie::parse($_COOKIE[$amp_cookie_name]);
  // For Browser SDK 2.0: AmplitudeCookie::parse($_COOKIE[$amp_cookie_name], true);
  $device_id = $cookie_data['deviceId'];
}
// If no device ID found, generate a new one and set the cookie
if ($device_id === null) {
  $device_id = uniqid('', true);
  $amp_cookie_value = AmplitudeCookie::generate($device_id);
  // For Browser SDK 2.0: AmplitudeCookie::generate($device_id, true);
  setcookie($amp_cookie_name, $amp_cookie_value, [
    'domain' => '.your-domain.com', // this should be the same domain used by the Amplitude JS SDK
    'httponly' => false,
    'secure' => false
  ]);
}

이 내용이 도움이 되었나요?