Con el SDK de PHP de Kameleoon, puede ejecutar experimentos y activar feature flags en su servidor PHP de back-end. Es sencillo integrar nuestro SDK en su aplicación web y su huella (memoria y uso de red) es baja.
Primeros pasos: Para obtener ayuda para comenzar, consulte la guía del desarrollador.
Changelog: Última versión del SDK de PHP: 4.23.0 Changelog.
Métodos del SDK: Para la documentación de referencia completa del SDK de PHP, consulte la sección referencia.
Guía del desarrollador
This guide is designed to help you integrate our SDK into your application code.
Primeros pasos
Primero debe instalar nuestro SDK. Una vez descomprimido, verá dos directorios: kameleoon/ y job/.
Instalación del cliente PHP (Composer package)
El paquete de instalación está disponible en Packagist. Puede instalar el SDK de PHP añadiéndolo como dependencia mediante Composer:
{
"require": {
"kameleoon/kameleoon-client-php": "^4.18.0"
}
}
Finally, execute the following command to regenerate the autoloader:
With a cron job (Recommended)
Setting up the cron allows the tracking of data added by the PHP sdk with the addData() method. However, if you are unable to install it, front end tracking can still be implemented following this guide.
El directorio job/ corresponde a un trabajo que debe ejecutarse mediante un planificador de tareas estándar (como cron).
Le sugerimos instalar el script en /usr/local/opt/kameleoon/kameleoon-client-php-process-queries.sh y usar nuestra entrada de crontab predeterminada. Sin embargo, puede instalarlo en otra ubicación y modificar la entrada de crontab en consecuencia.
Without a cron job
If you cannot install the cron job, you can use Kameleoon in hybrid mode to benefit from the Kameleoon Application Engine’s, engine.js (previously named, kameleoon.js) tracking capabilities. Our SDK provides the getEngineTrackingCode() method, which sends exposure events to Kameleoon or any other analytics solution you use on your website.
With this approach you won’t be able to track data added with the addData() method of the PHP SDK.
In other words, the only way for the PHP SDK to collect and process experiment data server-side is through the cron job.
The hybrid mode is useful for tracking purposes, but does not enable backend data collection.
Configuración adicional
You can customize the behavior of the PHP SDK via a configuration file. We provide a sample configuration file named client-php.json.sample in the SDK archive. You can also download a sample configuration file. We suggest to install this file to the default path of /tmp/kameleoon/client-php.json. La siguiente tabla muestra las propiedades disponibles que puede configurar:
| Clave | Descripción | Valor predeterminado |
|---|
clientId / client_id (obligatorio) | Necesario para la autenticación con el servicio de Kameleoon. Para encontrar su client_id, consulte la documentación de credenciales de API. | |
clientSecret / client_secret (obligatorio) | Necesario para la autenticación con el servicio de Kameleoon. Para encontrar su client_secret, consulte la documentación de credenciales de API. | |
kameleoonWorkDir / kameleoon_work_dir (opcional) | Specifies a working directory for the PHP client (which will create files in this directory). The directory needs to be writable by the PHP user. | /tmp/kameleoon/client-php/ |
refreshIntervalMinute / refresh_interval_minute (opcional) | Specifies the refresh interval, in minutes, that the SDK fetches the configuration for the active experiments and feature flags. The value determines the maximum time it takes to propagate changes, such as activating or deactivating feature flags or launching experiments, to your production servers. | 60 minutos |
defaultTimeoutMillisecond / default_timeout_millisecond (opcional) | Specifies the timeout, in milliseconds, for network requests from the SDK. Set the value to 30 seconds or more if you do not have a stable connection. Some methods have an additional parameter that you can use to override the default timeout for that particular method. If you do not specify the timeout for a method explicitly, the SDK uses this default value. | 10000 milisegundos |
cookieOptions->topLevelDomain / cookie_options.domain (obligatorio en modo híbrido) | El dominio de nivel superior actual de su sitio web. Use el formato: example.com. No incluya https://, www ni otros subdominios. Kameleoon utiliza esta información para establecer la cookie correspondiente en el dominio de nivel superior. | null |
cookieOptions->secure / cookie_options.secure (opcional) | Controls the Secure cookie attribute. | false |
cookieOptions->httpOnly / cookie_options.http_only (opcional) | Controls the HttpOnly cookie attribute. | false |
cookieOptions->sameSite / cookie_options.samesite (opcional) | Controls the SameSite cookie attribute. | Lax |
environment / environment (opcional) | Entorno desde el cual se debe utilizar la configuración del feature flag. El valor puede ser production, staging o development. Consulte el artículo de gestión de entornos para más detalles. | production |
networkDomain / network_domain (opcional) | Dominio personalizado utilizado por los SDKs para las solicitudes salientes, a menudo para proxy. Debe ser un dominio válido (por ejemplo, example.com o sub.example.com). Los formatos no válidos se sustituyen por el valor de Kameleoon. | null |
requestBodySizeLimitBytes / request_body_size_limit_bytes (optional) | Limits the size of tracking packages (in bytes) — files that store data collected between cron job runs. In some cases, reducing the package size may be necessary due to server or network restrictions. The maximum allowed value is 2.5 MB (2621440 bytes). | 2621440 |
debugMode / debug_mode (deprecated) | The parameter sends additional information to our tracking servers to help analyze issues. It should usually be off (false), but activating it (true) has no impact on SDK performance. This field is deprecated and will be removed in SDK version 5.0.0. Use KameleoonLogger::setLogLevel instead. | false |
If you do not use the default path (/tmp/kameleoon/client-php.json) for the configuration file, you will need to:
- pass your configuration file’s path as a third argument to the
KameleoonClientFactory::create() method;
- modify your crontab entry to add the —conf argument to the job script (so, for instance, it would be
bash /usr/local/opt/bin/kameleoon-client-php-process-queries.sh --conf /my/path/kameleoon.json).
To learn more about client_id and client_secret, and how to obtain them, refer to the API credentials article. Tenga en cuenta que el Kameleoon PHP SDK uses the Automation API and follows the OAuth 2.0 client credentials flow.
Inicialización del cliente Kameleoon
After installing the SDK into your application and configuring the correct credentials (in /tmp/kameleoon/client-php.json), the next step is to create the Kameleoon client in your application code. Por ejemplo:
require "vendor/autoload.php";
use Kameleoon\KameleoonClientConfig;
use Kameleoon\KameleoonClientFactory;
use Kameleoon\Exception\ConfigCredentialsInvalid;
use Kameleoon\Exception\KameleoonException;
use Kameleoon\Exception\SiteCodeIsEmpty;
$siteCode = "a8st4f59bj";
try {
// Read from default configuration path: "/tmp/kameleoon/php-client/"
$kameleoonClient = KameleoonClientFactory::create($siteCode);
} catch (SiteCodeIsEmpty $ex) {
// indicates that provided site code is empty
} catch (ConfigCredentialsInvalid $ex) {
// indicates that provided clientId / clientSecret are not valid
} catch (KameleoonException $ex) {
// probably indicates that the SDK is unable to access the **Kameleoon working directory**
}
try {
$kameleoonClient = KameleoonClientFactory::create($siteCode, "custom/file/path/client-php.json");
} catch (SiteCodeIsEmpty $ex) {
// indicates that provided site code is empty
} catch (ConfigCredentialsInvalid $ex) {
// indicates that provided clientId / clientSecret are not valid
} catch (KameleoonException $ex) {
// probably indicates that the SDK is unable to access the **Kameleoon working directory**
}
try {
$cookieOptions = KameleoonClientConfig::createCookieOptions(
"example.com", // domain: optional, but strictly recommended
false, // secure: optional (false by default)
false, // httponly: optional (false by default)
"Lax" // samesite: optional (Lax by default)
);
$config = new KameleoonClientConfig(
"<clientId>", // clientId: mandatory
"<clientSecret>", // clientSecret: mandatory
"/tmp/kameleoon/php-client/", // kameleoonWorkDir: optional / ("/tmp/kameleoon/php-client/" by default)
60, // refreshIntervalMinute: in minutes, optional (60 minutes by default)
10_000, // defaultTimeoutMillisecond: in milliseconds, optional (10_000 ms by default)
false, // debugMode: optional (false by default)
$cookieOptions, // cookieOptions: optional
"development", // environment: optional ("production" by default)
"example.com", // networkDomain: optional (null by default)
1024*1024, // requestBodySizeLimitBytes: optional (2560 * 1024 by default)
);
$kameleoonClient = KameleoonClientFactory::createWithConfig($siteCode, $config);
} catch (SiteCodeIsEmpty $ex) {
// indicates that provided site code is empty
} catch (ConfigCredentialsInvalid $ex) {
// indicates that provided clientId / clientSecret are not valid
} catch (KameleoonException $ex) {
// probably indicates that the SDK is unable to access the **Kameleoon working directory**
}
A KameleoonClient is a singleton object that acts as a bridge between your application and the Kameleoon platform. It includes all the methods and properties you need to run an experiment. Tenga en cuenta que el SDK takes its settings from a configuration file. De forma predeterminada, the path /tmp/kameleoon/client-php.json will be used, but you can use a different path for the configuration file by providing an optional third argument to the KameleoonClientFactory::create() method.
It’s your responsibility as the application developer to use correct logic in your application code within the context of A/B testing via Kameleoon. A good practice is to always assume that the current visitor can be left out of the experiment because the experiment has not yet been launched. Leaving out the current visitor is simple, as it corresponds to the implementation of the default / reference variation logic. The code samples in the next paragraph show examples of such an approach.
Activación de un feature flag
Asignación de un ID único a un usuario
Para asignar un ID único a un usuario, puede utilizar el método getVisitorCode(). Si no existe un visitor code (en la cookie de los encabezados de la solicitud), el método genera un ID único aleatorio o utiliza un defaultVisitorCode que usted haya generado. A continuación, el ID se establece en una cookie en los encabezados de respuesta.
Si está usando Kameleoon en modo híbrido, llamar al método getVisitorCode() garantiza que el ID único (visitor code) se comparta entre el archivo de aplicación engine.js (anteriormente llamado kameleoon.js) y el SDK.
Recuperación de la configuración de un flag
Para implementar un feature flag en su código, primero debe crear el feature flag en su cuenta de Kameleoon.
Para determinar el estado o la variación de un feature flag para un usuario específico, debe utilizar el método getVariation() o isFeatureActive() para recuperar la configuración basada en el featureKey.
El método getVariation() gestiona tanto los feature flags simples con estados ON/OFF como los flags más complejos con múltiples variaciones. El método recupera la variación adecuada para el usuario comprobando las reglas de la funcionalidad, asignando la variación y devolviéndola en función del featureKey y el visitorCode.
El método isFeatureActive() puede utilizarse si desea recuperar la configuración de un feature flag simple que solo tiene un estado ON u OFF, a diferencia de los feature flags más complejos con múltiples variaciones u opciones de segmentación.
If your feature flag has associated variables (such as specific behaviors tied to each variation) getVariation() also enables you to access the Variation object, which provides details about the assigned variation and its associated experiment. This method checks whether the user is targeted, finds the visitor’s assigned variation, and saves it to storage. When track=true, the SDK will send the exposure event to the specified experiment on one of the next tracking request, which is automatically performed by the cron job. De forma predeterminada, its interval is 1 minute.
El método getVariation() le permite controlar si se realiza el seguimiento. Si track=false, el SDK no enviará eventos de exposición. Esto es útil si prefiere no realizar el seguimiento de los datos a través del SDK y, en su lugar, basarse en el seguimiento del lado del cliente gestionado por el motor de Kameleoon, por ejemplo. Además, establecer track=false resulta útil cuando se utiliza el método getVariations(), donde puede que solo necesite las variaciones de todos los flags sin desencadenar eventos de seguimiento. Si desea saber más sobre cómo funciona el seguimiento, consulte este artículo
Adición de puntos de datos para segmentar a un usuario o filtrar / desglosar visitas en informes
Para segmentar a un usuario, asegúrese de haber añadido los puntos de datos relevantes a su perfil antes de recuperar la variación de la funcionalidad o comprobar si el flag está activo. Utilice el método addData() para añadir estos puntos de datos al perfil del usuario.
Para recuperar puntos de datos recopilados en otros dispositivos o acceder a datos pasados del usuario (recopilados en el lado del cliente cuando se utiliza Kameleoon en modo híbrido), utilice el método getRemoteVisitorData(). Este método obtiene datos de los servidores de forma asíncrona. Es importante llamar a getRemoteVisitorData() antes de recuperar la variación o comprobar si el feature flag está activo, ya que estos datos pueden ser necesarios para asignar a un usuario a una variación determinada.
Para obtener más información sobre las condiciones de segmentación disponibles, consulte el artículo detallado sobre este tema.
Además, los puntos de datos que añade al perfil del visitante estarán disponibles al analizar sus experimentos, lo que le permite filtrar y desglosar sus resultados por factores como el dispositivo y el navegador. El modo híbrido de Kameleoon recopila automáticamente una variedad de puntos de datos en el lado del cliente, lo que facilita desglosar sus resultados en función de estos puntos de datos previamente recopilados. Consulte la lista completa aquí.
Si necesita realizar el seguimiento de puntos de datos adicionales más allá de los que se recopilan automáticamente, puede utilizar la funcionalidad de Custom Data de Kameleoon. Custom Data le permite capturar y analizar información específica relevante para sus experimentos. No olvide llamar al método flush() para enviar los datos recopilados a los servidores de Kameleoon para su análisis.
Para asegurarse de que sus resultados sean precisos, se recomienda filtrar los bots utilizando el tipo de dato UserAgent.
Seguimiento de conversiones de objetivos
Cuando un usuario completa una acción deseada (como realizar una compra), se registra como una conversión. Para hacer seguimiento de las conversiones, utilice el método trackConversion() y proporcione los parámetros requeridos visitorCode y goalId.
La solicitud de seguimiento de conversiones se enviará junto con la siguiente solicitud de seguimiento programada, que el SDK envía a intervalos regulares (definidos en el crontab de intervalo de seguimiento). Si prefiere enviar la solicitud de inmediato, utilice el método flush() con el parámetro instant=true.
Envío de eventos a soluciones de analítica
Para realizar el seguimiento de las conversiones y enviar eventos de exposición a su solución de analítica de cliente, primero debe implementar Kameleoon en modo híbrido. A continuación, utilice el método getEngineTrackingCode().
El método getEngineTrackingCode() recupera el código de seguimiento único necesario para enviar eventos de exposición a su solución de analítica. El uso de este método le permite registrar eventos y enviarlos a la plataforma de analítica que desee.
Experimentación entre dispositivos
Para dar soporte a los visitantes que acceden a una aplicación desde varios dispositivos, Kameleoon permite sincronizar los datos del visitante previamente recopilados entre cada uno de sus dispositivos y reconciliar su historial de visitas entre dispositivos mediante la experimentación entre dispositivos. Los casos de estudio y la información detallada sobre cómo Kameleoon gestiona los datos entre dispositivos están disponibles en el artículo sobre experimentación entre dispositivos.
Sincronización de datos personalizados entre dispositivos
Aunque la sincronización de mapeo personalizado se utiliza para alinear los datos del visitante entre dispositivos, no siempre es necesaria. A continuación se presentan dos escenarios en los que no se requiere la sincronización de mapeo personalizado:
Mismo ID de usuario en todos los dispositivos
Si el mismo ID de usuario se utiliza de forma consistente en todos los dispositivos, la sincronización se gestiona automáticamente sin necesidad de una sincronización de mapeo personalizado. Basta con llamar al método getRemoteVisitorData() cuando desee sincronizar los datos recopilados entre varios dispositivos.
Instancias multi-servidor con IDs consistentes
En configuraciones complejas que involucran varios servidores (por ejemplo, instancias de servidor distribuidas), donde el mismo ID de usuario está disponible en todos los servidores, la sincronización entre servidores (con getRemoteVisitorData()) es suficiente sin necesidad de una sincronización adicional de mapeo personalizado.
Los clientes que necesiten datos adicionales pueden consultar la descripción del método getRemoteVisitorData() para obtener más orientación. En el código siguiente se asume que el mismo identificador único (en este caso, el visitorCode, que también puede denominarse userId) se utiliza de manera consistente entre los dos dispositivos para una recuperación precisa de los datos.
Si desea sincronizar los datos recopilados en tiempo real, debe elegir el ámbito Visitor para sus datos personalizados.
// In this example, Custom data with index `90` was set to "Visitor" scope on Kameleoon.
const VISITOR_SCOPE_CUSTOM_DATA_INDEX = 90;
$kameleoonClient->addData($visitorCode, new CustomData(VISITOR_SCOPE_CUSTOM_DATA_INDEX, "your data"));
$kameleoonClient->flush($visitorCode);
// Call the `getRemoteVisitorData` method before working with the data.
$kameleoonClient->getRemoteVisitorData($visitorCode);
// After the call, the SDK on Device B will have access to CustomData of Visitor scope defined on Device A.
// So, "your data" will be available to target and track the visitor.
Uso de datos personalizados para la fusión de sesiones
La experimentación entre dispositivos permite combinar el historial de un visitante en cada uno de sus dispositivos (reconciliación de historial). La reconciliación de historial permite fusionar diferentes sesiones de un visitante en una sola. Para reconciliar el historial de visitas, utilice CustomData para proporcionar un identificador único del visitante. Para más información, consulte la documentación dedicada.
Una vez habilitada la reconciliación entre dispositivos, al llamar a getRemoteVisitorData() con el parámetro userId se recuperan todos los datos conocidos para un usuario determinado.
Las sesiones con el mismo identificador siempre verán la misma variación en un experimento. En la vista Visitor de las páginas de resultados de su experimento, estas sesiones aparecerán como un único visitante.
La configuración del SDK garantiza que las sesiones asociadas siempre vean la misma variación del experimento. Sin embargo, existen algunas limitaciones en cuanto a la asignación de variaciones entre dispositivos. Estas limitaciones se describen aquí.
Siga la guía de activación de la reconciliación de historial entre dispositivos para configurar sus datos personalizados en la plataforma Kameleoon.
Posteriormente, puede usar el SDK de forma normal. Los siguientes métodos pueden ser útiles en el contexto de la fusión de sesiones:
getRemoteVisitorData() con UniqueIdentifier(true) añadido: para recuperar datos de todos los visitantes vinculados.
trackConversion() o flush() con datos UniqueIdentifier(true) añadidos: para hacer seguimiento de datos de un visitante específico asociado con otro visitante.
A continuación se muestra un ejemplo de cómo usar datos personalizados para la fusión de sesiones.
// In this example, `91` represents the Custom Data's index
// configured as a unique identifier in Kameleoon.
const MAPPING_INDEX = 91;
const FEATURE_KEY = "ff123";
// 1. Before the visitor is authenticated
// Retrieve the variation for an unauthenticated visitor.
// Assume `anonymousVisitorCode` is the randomly generated ID for that visitor.
$anonymousVariation = $kameleoonClient->getVariation($anonymousVisitorCode, FEATURE_KEY);
// 2. After the visitor is authenticated
// Assume `userId` is the authenticates visitor's visitor code.
$kameleoonClient->addData($anonymousVisitorCode, new CustomData(MAPPING_INDEX, $userId));
$kameleoonClient->flush($anonymousVisitorCode, null, null, true);
// Indicate that `userId` is a unique identifier.
$kameleoonClient->addData($userId, new UniqueIdentifier(true));
// 3. After the visitor has been authenticated
// Retrieve the variation for the `userId`, which will match the anonymous visitor code's variation.
$userVariation = $kameleoonClient->getVariation($userId, FEATURE_KEY);
$isSameVariation = $userVariation->key == $anonymousVariation->key; // true
// The `userId` and `anonymousVisitorCode` are now linked and tracked as a single visitor.
$kameleoonClient->trackConversion($userId, 123, 10.0);
// Additionally, the linked visitors will share all fetched remote visitor data.
$kameleoonClient->getRemoteVisitorData($userId);
En este ejemplo, la aplicación tiene una página de inicio de sesión. Como el ID de usuario es desconocido en el momento del inicio de sesión, se utiliza un identificador de visitante anónimo generado por el método getVisitorCode(). Después de que el usuario inicia sesión, el visitante anónimo se asocia con el ID de usuario y se utiliza como identificador único del visitante.
Uso de una clave de bucketing personalizada
De forma predeterminada, Kameleoon utiliza un ID de visitante anónimo y único (visitorCode) para asignar usuarios a las variaciones de los feature flags. Este ID se genera y almacena habitualmente en el dispositivo del usuario (en una cookie del navegador para los SDKs del lado del cliente y del lado del servidor, y en almacenamiento persistente para los SDKs móviles). Sin embargo, en determinados escenarios puede necesitar asegurarse de que todos los usuarios de la misma organización vean la misma variante de un feature flag.
La opción Custom Bucketing Key le permite anular este comportamiento predeterminado proporcionando su propio identificador personalizado para el bucketing. Esta anulación garantiza que la lógica de asignación de Kameleoon utilice la clave que usted especifique en lugar del visitorCode predeterminado.
Casos de uso
El uso de una clave de bucketing personalizada es esencial para mantener la consistencia y precisión en las asignaciones de sus feature flags, especialmente en estas situaciones:
- Experimentos a nivel de cuenta u organización: Para productos B2B o escenarios en los que desea asignar a todos los usuarios de la misma organización a la misma variación, puede utilizar un identificador como
accountId. Las claves de bucketing personalizadas son cruciales para probar mediante A/B funcionalidades que afecten a todo un equipo o empresa.
Al implementar una clave de bucketing personalizada, garantiza una mayor consistencia y precisión en sus experimentos, lo que se traduce en resultados más fiables y en una mejor experiencia de usuario.
Detalles técnicos
Cuando configura una clave de bucketing personalizada para un feature flag, proporciona a Kameleoon un identificador específico de los datos de su aplicación:
$kameleoonClient->addData($visitorCode, new Kameleoon\Data\CustomData(1, "newVisitorCode"));
- Proporcionar la clave personalizada: Usted proporciona su identificador personalizado al SDK de Kameleoon mediante el método
addData(). En este método, pasará la clave de bucketing personalizada que haya elegido como un objeto CustomData. Aquí, newVisitorCode hace referencia al identificador que desea usar para el bucketing (por ejemplo, el nuevo userId o accountId).
Para que la clave de bucketing personalizada funcione correctamente, también debe definirse y configurarse para el feature flag durante el proceso de creación o edición del flag. Sin esta configuración correspondiente, el bucketing del SDK no aplicará su clave personalizada. Para obtener instrucciones detalladas sobre cómo configurar esto en Kameleoon, consulte este artículo.
- Lógica de bucketing: Una vez que se proporciona una clave de bucketing personalizada a través del método
addData(), todos los cálculos de hash para asignar usuarios a las variaciones utilizarán este newVisitorCode (su clave personalizada) en lugar del visitorCode predeterminado. Usar el newVisitorCode significa que la decisión de bucketing queda ligada a su identificador personalizado, garantizando asignaciones consistentes en los diversos contextos en los que esté presente ese identificador.
- Seguimiento de datos y analítica: Es crucial tener en cuenta que, aunque el
newVisitorCode (su clave personalizada) se utiliza para las decisiones de bucketing, todos los datos posteriores (eventos de seguimiento y conversiones, por ejemplo) se envían y se asocian con el visitorCode original. Esta separación garantiza que su analítica refleje con precisión los recorridos e interacciones individuales de los usuarios dentro del contexto más amplio de su experimento, incluso cuando el bucketing se realiza a un nivel superior (como una cuenta) o a través de varios dispositivos/sesiones. Sus datos originales del visitante permanecen intactos para una elaboración de informes completa.
Requisitos técnicos
Para utilizar eficazmente una clave de bucketing personalizada:
- The key must be a
string.
- Debe ser única para la entidad que pretende agrupar (por ejemplo, si utiliza un
userId, el ID de cada usuario debe ser único).
- La clave debe estar disponible para el SDK en el momento exacto en que se evalúa la decisión del feature flag para ese usuario o solicitud.
Condiciones de segmentación
Los SDKs de Kameleoon admiten una variedad de condiciones de segmentación predefinidas que puede usar para segmentar a los usuarios en sus campañas. Para ver la lista de condiciones que admite este SDK, consulte usar el historial de visitas para segmentar a los usuarios.
También puede utilizar sus propios datos externos para segmentar a los usuarios.
Registro de eventos
El SDK genera registros que reflejan diversos procesos internos y problemas.
Niveles de registro
El SDK admite la configuración para limitar el registro mediante un nivel de log.
use Kameleoon\logging\KameleoonLogger;
use Kameleoon\logging\LogLevel;
// The `NONE` log level does not allow logging.
KameleoonLogger::setLogger(LogLevel::NONE);
// The `ERROR` log level only allows logging issues that may affect the SDK's primary behavior.
KameleoonLogger::setLogger(LogLevel::ERROR);
// The `WARNING` log level allows logging issues which may require additional attention.
// It extends the `ERROR` log level.
// The `WARNING` log level is a default log level.
KameleoonLogger::setLogger(LogLevel::WARNING);
// The `INFO` log level allows logging general information on the SDK's internal processes.
// It extends the `WARNING` log level.
KameleoonLogger::setLogger(LogLevel::INFO);
// The `DEBUG` level logs additional details about the SDK’s internal processes and extends the `INFO` level
// with more granular. diagnostic output.
// This information is not intended for end-user interpretation but can be sent to our support team
// to assist with internal troubleshooting.
KameleoonLogger::setLogger(LogLevel::DEBUG);
Gestión personalizada de los registros
El SDK escribe sus registros en la salida de la consola de forma predeterminada. Este comportamiento puede anularse.
El filtrado por nivel de log se realiza de forma independiente de la lógica de gestión de los registros.
use Kameleoon\logging\KameleoonLogger;
use Kameleoon\logging\Logger;
use Kameleoon\logging\LogLevel;
use Monolog\Logger as MonologLogger;
public class CustomLogger implements Logger {
// Monolog logger
private MonologLogger $inner;
public function __construct(MonologLogger $inner)
{
$this->inner = $inner;
}
// `log` method accepts logs from the SDK
public function log($level, string $message): void
{
// Custom log handling logic here. For example:
switch ($level) {
case LogLevel::ERROR:
$this->inner->error($message);
break;
case LogLevel::WARNING:
$this->inner->warning($message);
break;
case LogLevel::INFO:
$this->inner->info($message);
break;
case LogLevel::DEBUG:
$this->inner->debug($message);
break;
}
}
}
// Log level filtering is applied separately from log handling logic.
// The custom logger will only accept logs that meet or exceed the specified log level.
// Ensure the log level is set correctly.
KameleoonLogger::setLogLevel(LogLevel::DEBUG); // Optional; defaults to `LogLevel::WARNING`.
KameleoonLogger::setLogger(new CustomLogger($inner));
Referencia
This is a full reference documentation of the PHP SDK.
Inicialización
create()
This method in Kameleoon\KameleoonClientFactory creates a KameleoonClient instance by providing your SDK configuration in a configuration file. You need to initialize the SDK by creating this instance of KameleoonClient before you can use other SDK methods. All interactions with the SDK use this KameleoonClient instance. To provide the configuration as a KameleoonClientConfig object instead, see the createWithConfig method.
require "vendor/autoload.php";
use Kameleoon\KameleoonClientFactory;
use Kameleoon\Exception\ConfigCredentialsInvalid;
use Kameleoon\Exception\KameleoonException;
use Kameleoon\Exception\SiteCodeIsEmpty;
$siteCode = "a8st4f59bj";
try {
// Read from default configuration path: "/tmp/kameleoon/php-client/"
$kameleoonClient = KameleoonClientFactory::create($siteCode);
} catch (SiteCodeIsEmpty $ex) {
// indicates that provided site code is empty
} catch (ConfigCredentialsInvalid $ex) {
// indicates that provided clientId / clientSecret are not valid
} catch (KameleoonException $ex) {
// probably indicates that the SDK is unable to access the **Kameleoon working directory**
}
try {
$kameleoonClient = KameleoonClientFactory::create($siteCode, "custom/file/path/client-php.json");
} catch (SiteCodeIsEmpty $ex) {
// indicates that provided site code is empty
} catch (ConfigCredentialsInvalid $ex) {
// indicates that provided clientId / clientSecret are not valid
} catch (KameleoonException $ex) {
// probably indicates that the SDK is unable to access the **Kameleoon working directory**
}
Argumentos
| Nombre | Tipo | Descripción |
|---|
| siteCode | String | Es la clave única del proyecto de Kameleoon que está utilizando con el SDK. Este campo es obligatorio. |
| configurationFilePath | String | Ruta al archivo de configuración del SDK. This field is optional and set to /tmp/kameleoon/client-php.json by default. |
Valor de retorno
| Type | Description |
|---|
| Kameleoon\KameleoonClient | An instance of the KameleoonClient class that will be used to manage your experiments and feature flags. |
Excepciones lanzadas
| Tipo | Descripción |
|---|
| SiteCodeIsEmpty | Exception indicating that the requested credentials were not provided (either using the configuration file or the config parameter in the method). |
| ConfigCredentialsInvalid | Exception indicating that the requested credentials were not provided (either using the configuration file or the config parameter in the method). |
| KameleoonException | Exception that may indicate that the SDK is unable to access the Kameleoon working directory. |
createWithConfig()
This method in Kameleoon\KameleoonClientFactory creates a KameleoonClient instance and allows you to pass your SDK configuration in a KameleoonClientConfig object. You need to initialize the SDK by creating this KameleoonClient instance before you can use other SDK methods. All interactions with the SDK use this KameleoonClient instance. To provide your SDK configuration in a file instead, use the create method.
require "vendor/autoload.php";
use Kameleoon\KameleoonClientConfig;
use Kameleoon\KameleoonClientFactory;
use Kameleoon\Exception\ConfigCredentialsInvalid;
use Kameleoon\Exception\KameleoonException;
use Kameleoon\Exception\SiteCodeIsEmpty;
$siteCode = "a8st4f59bj";
try {
$cookieOptions = KameleoonClientConfig::createCookieOptions(
"example.com", // domain: optional, but strictly recommended
false, // secure: optional (false by default)
false, // httponly: optional (false by default)
"Lax" // samesite: optional (Lax by default)
);
$config = new KameleoonClientConfig(
"<clientId>", // clientId: mandatory
"<clientSecret>", // clientSecret: mandatory
"/tmp/kameleoon/php-client/", // kameleoonWorkDir: optional / ("/tmp/kameleoon/php-client/" by default)
60, // refreshIntervalMinute: in minutes, optional (60 minutes by default)
10_000, // defaultTimeoutMillisecond: in milliseconds, optional (10_000 ms by default)
false, // debugMode: optional (false by default)
$cookieOptions, // cookieOptions: optional
"development", // environment: optional ("production" by default)
"example.com", // networkDomain: optional (null by default)
1024*1024, // requestBodySizeLimitBytes: optional (2560 * 1024 by default)
);
$kameleoonClient = KameleoonClientFactory::create($siteCode, $config);
} catch (SiteCodeIsEmpty $ex) {
// indicates that provided site code is empty
} catch (ConfigCredentialsInvalid $ex) {
// indicates that provided clientId / clientSecret are not valid
} catch (KameleoonException $ex) {
// probably indicates that the SDK is unable to access the **Kameleoon working directory**
}
Argumentos
| Nombre | Tipo | Descripción |
|---|
| siteCode | String | Code of the website you want to run experiments on. This unique code ID can be found in the Kameleoon app. Este campo es obligatorio. |
| kameleoonConfig | KameleoonClientConfig | Configuration SDK object that you pass. Este campo es opcional. |
Valor de retorno
| Tipo | Descripción |
|---|
| KameleoonClient | An instance of the KameleoonClient class that you use to manage your experiments and feature flags. |
Excepciones lanzadas
| Tipo | Descripción |
|---|
| SiteCodeIsEmpty | Exception indicating that the requested credentials were not provided (either using the configuration file or the config parameter in the method). |
| ConfigCredentialsInvalid | Exception indicating that the requested credentials were not provided (either using the configuration file or the config parameter in the method). |
| KameleoonException | Exception that may indicate that the SDK is unable to access the Kameleoon working directory. |
Feature flags y variaciones
isFeatureActive()
- 📨 Envía datos de seguimiento a Kameleoon (dependiendo del parámetro
track)
This method was previously called activateFeature, which was removed in SDK version 4.0.0.
Este método toma un visitorCode and featureKey as mandatory arguments to check if the specified feature will be active for a given user.
If such a user has never been associated with this feature flag, the SDK returns a boolean value randomly (true if the user should have this feature or false if not). If a user with a given visitorCode is already registered with this feature flag, it will detect the previous FeatureFlag value.
You have to make sure that proper error handling is set up in your code como se muestra en el ejemplo to the right to catch potential exceptions.
If you specify a visitorCode, the isFeatureActive() method uses it as the unique visitor identifier, which is useful for cross-device experimentation. Cuando especifica un visitorCode y establece el parámetro isUniqueIdentifier en true, el SDK vincula los datos vaciados con el visitante asociado al identificador especificado.
El parámetro isUniqueIdentifier está obsoleto. Utilice en su lugar UniqueIdentifier.isUniqueIdentifier también puede ser útil en otros escenarios excepcionales, como cuando no puede acceder al visitorCode anónimo asignado originalmente al visitante, pero sí tiene acceso a un ID interno conectado al visitante anónimo mediante la fusión de sesiones.
Kameleoon uses tracking to count sessions and visitors when you call certain methods, such as isFeatureActive(), getVariation() or getVariations().Use el valor predeterminado true para el parámetro track cuando exponga a los visitantes a una variación y necesite contarlos. Establezca el parámetro track en false solo si llama a estos métodos antes de exponer a los visitantes.Por ejemplo, if you call getVariations() to retrieve all variations before you expose visitors, set the track parameter to false. This setting prevents Kameleoon from prematurely counting a session. You can then trigger tracking later when you explicitly expose the visitor.Kameleoon sends tracking data every second by default. You can configure this interval up to five seconds using the tracking interval configuration option. Kameleoon groups tracking events into a single session as long as the interval between events is less than 30 minutes. If more than 30 minutes elapse between tracking events, Kameleoon counts the events as separate sessions. A visit appears in your reports 30 minutes after the last recorded event in the session.
$visitorCode = $kameleoonClient->getVisitorCode();
$featureKey = "new_checkout";
$hasNewCheckout = false;
try {
$hasNewCheckout = $kameleoonClient->isFeatureActive($visitorCode, $featureKey, $timeout);
// disabling tracking
$hasNewCheckout = $kameleoonClient->isFeatureActive($visitorCode, $featureKey, $timeout, null, false);
} catch (Kameleoon\Exception\FeatureNotFound $e) {
// Feature toggle not yet activated on Kameleoon's side - we consider the feature inactive.
$hasNewCheckout = false;
} catch (Kameleoon\Exception\VisitorCodeInvalid $e) {
// VisitorCode, which you passed to a method, is invalid and can't be accepted.
} catch (Kameleoon\Exception\DataFileInvalid $e) {
// It appears that the configuration has not been loaded and
// there is no previously saved version of the configuration available.
} catch (Exception $e) {
// This is a generic Exception handler which will handle all exceptions.
echo "Exception: ", $e->getMessage(), "\n";
}
if ($hasNewCheckout) {
// Implement new checkout code here.
}
The isFeatureActive() method evaluates the served variant, not the master flag state. If you exclude rules, the method uses the Then, for everyone else serve default state. If you select Off for this default state, the method always returns false even when the master feature flag is On.
Argumentos
| Nombre | Tipo | Descripción |
|---|
| visitorCode | string | Identificador único del usuario. Este campo es obligatorio. |
| featureKey | string | Clave de la funcionalidad que desea exponer a un usuario. Este campo es obligatorio. |
| timeout | ?int | Timeout (in milliseconds). This parameter specifies the maximum amount of time the method can block to wait for a result. Este campo es opcional. If a timeout value is not provided, the SDK uses the default_timeout specified in your configuration. |
| isUniqueIdentifier (Obsoleto) | ?bool | Parámetro opcional para indicar si el visitorCode es un identificador único. If not provided, el valor predeterminado es null. The field is optional. |
| track | bool | An optional parameter to enable or disable tracking of the feature evaluation (true by default). |
Valor de retorno
| Tipo | Descripción |
|---|
| bool | Value of the feature flag that is registered for a given visitorCode. |
Excepciones lanzadas
| Tipo | Descripción |
|---|
| FeatureNotFound | Exception indicating that the requested feature ID has not been found in the internal configuration of the SDK. This is usually normal and means that the feature flag has not yet been activated on Kameleoon’s side (but code implementing the feature is already deployed on the web-application’s side). |
| VisitorCodeInvalid | Exception indicating that the provided visitor code is not valid (empty, or longer than 255 characters). |
| DataFileInvalid | Exception indicating that the configuration has not been loaded and there is no previously saved version of the configuration available. |
getVariation()
- 📨 Envía datos de seguimiento a Kameleoon (dependiendo del parámetro
track)
Recupera la Variation asignada a un visitante dado para un feature flag específico.
Este método toma un visitorCode and featureKey as mandatory arguments. The track argument is optional and defaults to true.
Devuelve la Variation asignada al visitante. Si el visitante no está asociado con ninguna regla de feature flag, el método devuelve la Variation predeterminada para el feature flag dado.
Asegúrese de implementar un manejo de errores adecuado en su código para gestionar las posibles excepciones.
La variación predeterminada se refiere a la variación asignada a un visitante cuando no coincide con ninguna regla de entrega predefinida para un feature flag. In other words, it is the fallback variation applied to all users who are not targeted by specific rules. Se representa como la variación en la sección “Then, for everyone else…” de la interfaz de administración.
$featureKey = "new_checkout";
try {
$variation = $kameleoonClient->getVariation($visitorCode, $featureKey);
// disabling tracking
$variation = $kameleoonClient->getVariation($visitorCode, $featureKey, false);
} catch (Kameleoon\Exception\FeatureNotFound $e) {
// An error has occurred; the feature flag isn't found in the current configuration.
} catch (Kameleoon\Exception\FeatureEnvironmentDisabled $e) {
// The feature flag is disabled for the environment.
} catch (Kameleoon\Exception\VisitorCodeInvalid $e) {
// The visitor code you passed to the method is invalid and can't be accepted by the SDK.
}
// Fetch a variable value for the assigned variation
$title = $variation->variables["title"]->value;
switch ($variation->key) {
case "on":
// Main variation key is selected for visitorCode
break;
case "alternative_variation":
// Alternative variation key
break;
default:
// Default variation key
break;
}
Argumentos
| Name | Type | Description | Default |
|---|
| visitorCode (obligatorio) | string | Identificador único del visitante. | |
| featureKey (obligatorio) | string | Clave de la funcionalidad que desea exponer a un visitante. | |
| track (opcional) | bool | Parámetro opcional para habilitar o deshabilitar el seguimiento de la evaluación de la funcionalidad. | true |
Valor de retorno
| Tipo | Descripción |
|---|
Variation | An assigned Variation to a given visitor for a specific feature flag. |
Excepciones lanzadas
| Tipo | Descripción |
|---|
VisitorCodeInvalid | Excepción que indica que el visitor code proporcionado no es válido. It is either empty or longer than 255 characters. |
FeatureNotFound | Excepción que indica que la clave de funcionalidad solicitada no se encontró en la configuración interna del SDK. Esto suele significar que el feature flag no está activado en la aplicación de Kameleoon (pero el código que implementa la funcionalidad ya está desplegado en la aplicación). |
FeatureEnvironmentDisabled | Excepción que indica que el feature flag está deshabilitado para el entorno actual del visitante (por ejemplo, production, staging o development). |
getVariations()
- 📨 Envía datos de seguimiento a Kameleoon (dependiendo del parámetro
track)
Recupera un map de objetos Variation asignados a un visitante dado para todos los feature flags.
Este método itera sobre todos los feature flags disponibles y devuelve la Variation asignada para cada flag asociado con el visitante especificado. It takes visitorCode as a mandatory argument, while onlyActive and track are optional.
- Si
onlyActive se establece en true, el método getVariations() devolverá las variaciones de los feature flags siempre que el usuario no esté asignado a la variación off.
- El parámetro
track controla si el método realizará el seguimiento de las asignaciones de variación. De forma predeterminada, it is set to true. Si se establece en false, el seguimiento estará deshabilitado.
El map devuelto consta de claves de feature flags como claves y su Variation correspondiente como valores. Si no se asigna ninguna variación para un feature flag, el método devuelve la Variation predeterminada para ese flag.
Se debe implementar un manejo de errores adecuado para gestionar las posibles excepciones.
La variación predeterminada se refiere a la variación asignada a un visitante cuando no coincide con ninguna regla de entrega predefinida para un feature flag. In other words, it is the fallback variation applied to all users who are not targeted by specific rules. Se representa como la variación en la sección “Then, for everyone else…” de la interfaz de administración.
try {
$variations = $kameleoonClient->getVariations($visitorCode);
// only active variations
$variations = $kameleoonClient->getVariations($visitorCode, true);
// disable tracking
$variations = $kameleoonClient->getVariations($visitorCode, $onlyActive, false);
} catch (Kameleoon\Exception\VisitorCodeInvalid $e) {
// Handle exception
}
Argumentos
| Name | Type | Description | Default |
|---|
| visitorCode (obligatorio) | string | Identificador único del visitante. | |
| onlyActive (opcional) | bool | Parámetro opcional que indica si se deben devolver las variaciones para los feature flags activos (true) o todos (false). | false |
| track (opcional) | bool | Parámetro opcional para habilitar o deshabilitar el seguimiento de la evaluación de la funcionalidad. | true |
Valor de retorno
| Tipo | Descripción |
|---|
array<string, Types\Variation> | Map que contiene los objetos Variation asignados de los feature flags utilizando las claves de las funcionalidades correspondientes. |
Excepciones lanzadas
| Tipo | Descripción |
|---|
VisitorCodeInvalid | Excepción que indica que el visitor code proporcionado no es válido. It is either empty or longer than 255 characters. |
setForcedVariation()
El método permite you to programmatically assign a specific Variation to a user, bypassing the standard evaluation process. Esto es especialmente valioso para experimentos controlados donde la lógica de evaluación habitual no es necesaria o debe omitirse. It can also be helpful in scenarios like debugging or custom testing.
Cuando se establece una variación forzada, esta anula la lógica de evaluación en tiempo real de Kameleoon. Processes like segmentation, targeting conditions, and algorithmic calculations are skipped. To preserve segmentation and targeting conditions during an experiment, set forceTargeting=false instead.
Simulated variations always take precedence in the execution order. If a simulated variation calculation is triggered, it will be fully processed and completed first.
A forced variation is treated the same as an evaluated variation. It is tracked in analytics and stored in the user context like any standard evaluated variation, ensuring consistency in reporting.
El método puede lanzar excepciones bajo ciertas condiciones (por ejemplo, parámetros no válidos, contexto del usuario o problemas internos). Proper exception handling is essential to ensure that your application remains stable and resilient.
It’s important to distinguish forced variations from simulated variations:
- Forced variations: Are specific to an individual experiment.
- Simulated variations: Affect the overall feature flag result.
$experimentId = 9516;
try {
// Forcing the variation "on" for the experiment 9516 for the visitor
$kameleoonClient->setForcedVariation($visitorCode, $experimentId, "on");
// Forcing the variation "on" while preserving segmentation and targeting conditions during the experiment
$kameleoonClient->setForcedVariation($visitorCode, $experimentId, "on", false);
// Resetting the forced variation for the experiment 9516 for the visitor
$kameleoonClient->setForcedVariation($visitorCode, $experimentId, null);
} catch (Kameleoon\Exception\KameleoonException $e) {
// Handling the error
}
Argumentos
| Name | Type | Description | Default |
|---|
| visitorCode (obligatorio) | string | Identificador único del visitante. | |
| experimentId (obligatorio) | int | Experiment Id que será segmentado y seleccionado durante el proceso de evaluación. | |
| variationKey (obligatorio) | ?string | Variation Key correspondiente a una Variation que debe forzarse como valor devuelto para el experimento. Si el valor es null, la variación forzada se restablecerá. | |
| forceTargeting (opcional) | bool | Indica si la segmentación para el experimento debe forzarse y omitirse (true) o aplicarse como en el proceso de evaluación estándar (false). | true |
| timeout (opcional) | ?int | Timeout (in milliseconds). This parameter specifies the maximum amount of time the method can block to wait for a result. If a timeout value is not provided, the SDK uses the default_timeout specified in your configuration. | null |
Excepciones lanzadas
| Tipo | Descripción |
|---|
VisitorCodeInvalid | Excepción que indica que el visitor code proporcionado no es válido. It is either empty or longer than 255 characters. |
FeatureExperimentNotFound | Excepción que indica que el experiment id solicitado no se encontró en la configuración interna del SDK. Esto suele ser normal y significa que el experimento correspondiente a la regla todavía no se ha activado del lado de Kameleoon. |
FeatureVariationNotFound | Excepción que indica que la variation key (id) solicitada no se ha encontrado en la configuración interna del SDK. Esto suele ser normal y significa que el experimento correspondiente a la variación todavía no se ha activado del lado de Kameleoon. |
En la mayoría de los casos, solo es necesario gestionar el error básico KameleoonException, como se muestra en el ejemplo. However, if different types of errors require a response, handle each one separately based on specific requirements. Additionally, for enhanced reliability, general language errors can be handled by including Exception.
evaluateAudiences()
- 📨 Envía datos de seguimiento a Kameleoon
Este método evalúa a los visitantes con respecto a todos los segmentos disponibles de Audiences Explorer y realiza el seguimiento de los que coinciden.
evaluateAudiences() should be called after all relevant visitor data has been set or updated, and just before getting a feature variation or checking a feature flag. Este enfoque garantiza que el visitante se evalúe con los datos más recientes disponibles, lo que permite una asignación precisa de audiencia basada en todos los criterios.
After calling this method, you can perform a detailed analysis of segment performance in Audiences Explorer.
try {
$kameleoonClient->evaluateAudiences($visitorCode);
} catch (Kameleoon\Exception\KameleoonException $e) {
// Handling the exception
}
Argumentos
| Nombre | Tipo | Descripción | Default |
|---|
| visitorCode (obligatorio) | string | Identificador único del visitante. | |
| timeout (opcional) | ?int | Timeout (in milliseconds). This parameter specifies the maximum amount of time the method can block to wait for a result. If a timeout value is not provided, the SDK uses the default_timeout specified in your configuration. | null |
Excepciones lanzadas
| Tipo | Descripción |
|---|
VisitorCodeInvalid | Excepción que indica que el visitor code proporcionado no es válido. It is either empty or longer than 255 characters. |
En la mayoría de los casos, solo es necesario gestionar el error básico KameleoonException, como se muestra en el ejemplo. However, if different types of errors require a response, handle each one separately based on specific requirements. Additionally, for enhanced reliability, general language errors can be handled by including Exception.
getDataFile()
To evaluate all feature flags, use getVariations(). Este método es más eficiente que llamar a DataFile e iterar por los flags con getVariation().
Devuelve la configuración actual del SDK como un objeto DataFile.
try {
$dataFile = $kameleoonClient->getDataFile();
} catch (Kameleoon\Exception\KameleoonException $e) {
// Recommended (but optional) safeguard for unexpected exceptions from third-party libraries
}
Argumentos
| Nombre | Tipo | Descripción |
|---|
| timeout (opcional) | ?int | Timeout (in milliseconds). This parameter specifies the maximum amount of time the method can block to wait for a result. If a timeout value is not provided, the SDK uses the default_timeout specified in your configuration. |
Valor de retorno
| Tipo | Descripción |
|---|
DataFile | El DataFile que contiene la configuración del SDK |
Datos del visitante
getVisitorCode()
Este método se llamaba anteriormente obtainVisitorCode, que fue eliminado en la versión 4.0.0 del SDK.
Llame a este método para obtener el visitorCode de Kameleoon del visitante actual. Llamarlo es especialmente importante al utilizar Kameleoon en un entorno mixto de front-end y back-end, donde se debe garantizar la consistencia en la identificación del usuario. La lógica de implementación se describe a continuación:
-
First, we check if there is a kameleoonVisitorCode cookie or query parameter associated with the current Solicitud HTTP. If so, we use this as the visitor identifier.
-
If no cookie or parameter is present in the current request, we have two options for generating an identifier. One option is to create a new identifier randomly, and the other is to use the defaultVisitorCode argument if it has been provided. This feature allows our customers to input their own identifiers as visitor codes, which can be beneficial; it seamlessly matches Kameleoon visitors with their own users, eliminating the need for extra look-ups in a matching table.
-
In any case, the server-side (via HTTP header) kameleoonVisitorCode cookie is set with the value. El método devuelve this visitor value.
Para más información, consulte este artículo.
If you provide your own visitorCode, its uniqueness must be guaranteed on your end - the SDK cannot check it. Also note that the length of visitorCode is limited to 255 characters. Any excess characters will throw an exception.
El método getVisitorCode() le permite establecer variaciones simuladas para un visitante. Cuando las cookies (de una request o document) contienen la clave kameleoonSimulationFFData, se omite el proceso de evaluación estándar. En su lugar, el método devuelve directamente una Variation basada en los datos proporcionados.Puede aplicar simulaciones de dos formas:
- Automatically (recommended): If using Kameleoon Web Experimentation or the SDK in Hybrid mode, the cookie is created automatically when simulating a variant’s display using the Simulation Panel.
- Manualmente: Establezca la cookie
kameleoonSimulationFFData manualmente.
It’s important to distinguish simulated variations from forced variations:
- Simulated variations: Affect the overall feature flag result.
- Forced variations: Are specific to an individual experiment.
⚙️ Manual setupAsegúrese de que la cookie kameleoonSimulationFFData siga este formato:
kameleoonSimulationFFData={"featureKey":{"expId":10,"varId":20}}: Simula la variación con varId del experimento expId para el featureKey indicado.
kameleoonSimulationFFData={"featureKey":{"expId":0}}: Simula la variación predeterminada (definida en la sección Then, for everyone else in Production, serve) para el featureKey indicado.
⚠️ To ensure proper functionality, the cookie value must be encoded as a URI component using a method such as encodeURIComponent.
require "vendor/autoload.php";
// The cookie's domain must be provided in the configuration file if no argument is given.
$visitorCode = $kameleoonClient->getVisitorCode();
// default visitor code provided
$visitorCode = $kameleoonClient->getVisitorCode($defaultVisitorCode);
Argumentos
| Nombre | Tipo | Descripción |
|---|
| defaultVisitorCode | String | This parameter will be used as the visitorCode if no existing kameleoonVisitorCode cookie is found on the request. This field is optional, and, by default, a random visitorCode will be generated. |
| timeout | ?int | Timeout (in milliseconds). This parameter specifies the maximum amount of time the method can block to wait for a result. Este campo es opcional. If a timeout value is not provided, the SDK uses the default_timeout specified in your configuration. |
Valor de retorno
| Tipo | Descripción |
|---|
| String | A visitorCode that will be associated with this particular user and should be used with most of the methods of the SDK. |
Excepciones lanzadas
| Type | Description |
|---|
| InvalidArgumentException | Exception indicating that the cookie’s domain value was not provided (either via the configuration file, or via the topLevelDomain parameter on the method). |
addData()
El método addData() añade datos de segmentación al almacenamiento para que otros métodos puedan utilizar los datos para decidir si segmentar o no al visitante actual.
El método addData() no devuelve ningún valor y no interactúa por sí mismo con los servidores backend de Kameleoon. En su lugar, todos los datos declarados se guardan para su transmisión futura mediante el método flush(). Este enfoque reduce el número de llamadas al servidor, ya que los datos se agrupan habitualmente en una única llamada al servidor que desencadena el flush().
El método trackConversion() también envía cualquier dato previamente asociado, al igual que flush(). The same holds true for getVariation() and getVariations() methods if an experimentation rule is triggered.
Cada visitante solo puede tener una instancia de datos asociados para la mayoría de los tipos de datos. However, CustomData is an exception. Visitors can have one instance of associated CustomData per index.
// Add a single data item (tracked by default)
$kameleoonClient->addData($visitorCode, new Kameleoon\Data\Browser(Kameleoon\Data\Browser::CHROME));
// Add multiple data items (tracked by default)
$kameleoonClient->addData(
$visitorCode,
new Kameleoon\Data\PageView("https://url.com", "title", [3]),
new Kameleoon\Data\UserAgent("UserAgent")
);
// Add multiple data items stored locally for targeting only (not sent to the Kameleoon Data API)
$kameleoonClient->addData(
$visitorCode,
false,
new Kameleoon\Data\PageView("https://url.com", "title", [3]),
new Kameleoon\Data\UserAgent("UserAgent")
);
Argumentos
| Nombre | Tipo | Descripción | Valor predeterminado |
|---|
| visitorCode (obligatorio) | string | Identificador único del visitante. | |
| track (opcional) | bool | Especifica si los datos añadidos son aptos para el seguimiento. Cuando se establece en false, los datos se almacenan localmente y se utilizan solo para la evaluación de segmentación; no se envían a la Data API de Kameleoon. | true |
| data (obligatorio) | ...Data | Colección de tipos de datos de Kameleoon. | |
Excepciones
| Tipo | Descripción |
|---|
VisitorCodeInvalid | Excepción que indica que el visitor code proporcionado no es válido. It is either empty or longer than 255 characters. |
flush()
- 📨 Envía datos de seguimiento a Kameleoon
The flush() method is responsible for sending the Kameleoon data linked to a specific visitor. It triggers a tracking request that includes all the data previously added with the addData method, which has not yet been sent during an earlier call to one of the methods. flush() is non-blocking, as the server call is made asynchronously, unless the instant parameter is set to true.
La función flush() le permite decidir cuándo se envían a nuestros servidores los datos vinculados a un visitorCode específico. Por ejemplo, si llama a addData() varias veces, digamos una docena, sería ineficiente enviar datos al servidor cada vez que realiza una llamada. En su lugar, puede recopilar todos los datos primero y luego llamar a flush() una sola vez al final para enviarlos todos a la vez.
Si especifica un visitorCode, el método flush() lo usa como identificador único del visitante, lo cual es útil para la experimentación entre dispositivos. Cuando especifica un visitorCode y establece el parámetro isUniqueIdentifier en true, el SDK vincula los datos vaciados con el visitante asociado al identificador especificado.
El parámetro isUniqueIdentifier está obsoleto. Utilice en su lugar UniqueIdentifier.isUniqueIdentifier puede ser útil en situaciones particulares; por ejemplo, si no puede acceder al visitorCode anónimo asignado a un visitante, pero puede usar un ID interno vinculado a ese visitante a través de la fusión de sesiones.
$visitorCode = $kameleoonClient->getVisitorCode();
$kameleoonClient->addData(
$visitorCode,
new Kameleoon\Data\Browser(Kameleoon\Data\Browser::CHROME).
new Kameleoon\Data\PageView("https://url.com", "title", array(3)),
new Kameleoon\Data\Conversion(32, 10, false)
);
$kameleoonClient->flush($visitorCode); // Interval tracking, non-blocking operation
$kameleoonClient->flush($visitorCode, null, null, true); // Instant tracking, blocking operation
// if you operate with unique ID
$kameleoonClient->addData($visitorCode, new Kameleoon\Data\UniqueIdentifier(true));
$kameleoonClient->flush($visitorCode);
Argumentos
| Nombre | Tipo | Descripción |
|---|
| visitorCode | string | Identificador único del usuario. Este campo es obligatorio. |
| timeout | ?int | Timeout (in milliseconds). This parameter specifies the maximum amount of time the method can block to wait for a result. Este campo es opcional. If a timeout value is not provided, the SDK uses the default_timeout specified in your configuration. |
| isUniqueIdentifier (Obsoleto) | ?bool | Parámetro opcional para indicar si el visitorCode es un identificador único. If not provided, el valor predeterminado es null. The field is optional. |
| instant | bool | Boolean flag indicating whether the data should be sent instantly (true) or according to the scheduled tracking interval (false). If not provided, el valor predeterminado es false. Este campo es opcional. |
getRemoteData()
Este método se llamaba anteriormente retrieveDataFromRemoteSource, que fue eliminado en la versión 4.0.0 del SDK.
The getRemoteData() method lets you retrieve data based on a key you provide for a specific siteCode (set in KameleoonClientFactory.create()). A Kameleoon server stores this data. The Data API is typically used to save this data on our remote servers. This method, combined with our scalable servers, makes storing large amounts of data easy. You can then access this data later for each visitor or user.
$test_value = $kameleoonClient->getRemoteData("test"); // default timeout will be used
$test_value = $kameleoonClient->getRemoteData("test", 1000); // 1000 milliseconds timeout
try {
$test_value = $kameleoonClient->getRemoteData("test");
} catch (Exception $e) {
// Timeout or Json Decoding Exception
}
Argumentos
| Nombre | Tipo | Descripción |
|---|
| key | string | The key that the data you try to get is associated with. Este campo es obligatorio. |
| timeout | ?int | Timeout (in milliseconds). This parameter specifies the maximum amount of time the method can block to wait for a result. Este campo es opcional. If a timeout value is not provided, the SDK uses the default_timeout specified in your configuration. |
Valor de retorno
| Tipo | Descripción |
|---|
| Object | Object associated with retrieving data for specific key. |
Excepciones lanzadas
| Tipo | Descripción |
|---|
| Exception | Exception indicating that the request timed out or retrieved data can’t be decoded with json_decode method. |
getRemoteVisitorData()
getRemoteVisitorData() es un método asíncrono para recuperar los datos de visitas de Kameleoon para el visitorCode desde la Data API de Kameleoon. El método añade data to storage for other methods to use when making targeting decisions.
Los datos obtenidos mediante este método desempeñan un papel importante cuando desea:
- use data collected from other devices.
- access a user’s history, such as previously visited pages during past visits.
- use data that is only accessible on the client-side, like datalayer variables and goals that only convert on the front-end.
Read this article for a better understanding of possible use cases.
De forma predeterminada, getRemoteVisitorData() automatically retrieves the latest stored custom data with scope=Visitor and attaches them to the visitor without the need to call the method addData(). It is particularly useful for synchronizing custom data between multiple devices.
El parámetro isUniqueIdentifier está obsoleto. Utilice en su lugar UniqueIdentifier.isUniqueIdentifier puede ser útil en situaciones particulares; por ejemplo, si no puede acceder al visitorCode anónimo asignado a un visitante, pero puede usar un ID interno vinculado a ese visitante a través de la fusión de sesiones.
$visitorCode = "visitorCode";
// Visitor data will be fetched and automatically added for `visitorCode`
$dataArray = $kameleoonClient->getRemoteVisitorData($visitorCode, null); // default timeout will be used
$dataArray = $kameleoonClient->getRemoteVisitorData($visitorCode, 1000); // 1000 milliseconds timeout
// If you only want to fetch data and add it yourself manually, set shouldAddData == `false`
$dataArray = $kameleoonClient->getRemoteVisitorData($visitorCode, null, false); // default timeout will be used
$dataArray = $kameleoonClient->getRemoteVisitorData($visitorCode, 1000, false); // 1000 milliseconds timeout
Argumentos
| Nombre | Tipo | Descripción |
|---|
| visitorCode | string | The visitor code for which you want to retrieve the assigned data. Este campo es obligatorio. |
| timeout | ?int | Timeout (in milliseconds). This parameter specifies the maximum amount of time the method can block to wait for a result. Este campo es opcional. If a timeout value is not provided, the SDK uses the default_timeout specified in your configuration. |
| addData | bool | Booleano que indica si el método debe añadir automáticamente los datos recuperados para un visitante. If not specified, el valor predeterminado es true. Este campo es opcional. |
| filter | Kameleoon\Types\RemoteVisitorDataFilter | Filter for specifying what data should be retrieved from visits, by default only CustomData is retrieved from the current and latest previous visit (new RemoteVisitorDataFilter(1, true, true) or new RemoteVisitorDataFilter()). Other filters parameters are set to false. This filed is optional. |
| isUniqueIdentifier (Obsoleto) | ?bool | Parámetro opcional para indicar si el visitorCode es un identificador único. If not provided, el valor predeterminado es null. The field is optional. |
Valor de retorno
| Tipo | Descripción |
|---|
array<Kameleoon\Data> | A list of data assigned to the given visitor. |
Uso de parámetros en getRemoteVisitorData()
El método getRemoteVisitorData() ofrece flexibilidad al permitirle definir varios parámetros al recuperar datos de los visitantes. Whether you’re targeting based on goals, experiments, or variations, the same approach applies across all data types.
Por ejemplo, let’s say you want to retrieve data on visitors who completed a goal “Order transaction”. Puede especificar parámetros dentro del método getRemoteVisitorData() para refinar su segmentación. For instance, if you want to target only users who converted on the goal in their last five visits, you can set the previousVisitAmount parameter to 5 and conversions to true.
La flexibilidad mostrada en este ejemplo no se limita a los datos de objetivos. Puede usar parámetros dentro del método getRemoteVisitorData() para recuperar datos sobre una variedad de comportamientos del visitante.
Here is the list of available Kameleoon\Types\RemoteVisitorDataFilter options:| Name | Type | Description | Default |
|---|
| previousVisitAmount (opcional) | int | Número de visitas previas de las que recuperar datos. Number between 1 and 25 | 1 |
| currentVisit (opcional) | bool | If true, current visit data will be retrieved | true |
| customData (opcional) | bool | If true, custom data will be retrieved. | true |
| pageViews (opcional) | bool | If true, page data will be retrieved. | false |
| geolocation (opcional) | bool | If true, geolocation data will be retrieved. | false |
| device (opcional) | bool | If true, device data will be retrieved. | false |
| browser (opcional) | bool | If true, browser data will be retrieved. | false |
| operatingSystem (opcional) | bool | If true, operating system data will be retrieved. | false |
| conversions (opcional) | bool | If true, conversion data will be retrieved. | false |
| experiments (opcional) | bool | If true, experiment data will be retrieved. | false |
| kcs (opcional) | bool | If true, Kameleoon Conversion Score (KCS) will be retrieved. Requires the AI Predictive Targeting add-on | false |
| visitorCode (opcional) | bool | If true, Kameleoon will retrieve the visitorCode from the most recent visit and use it for the current visit. This is necessary if you want to ensure that the visitor, identified by their visitorCode, always receives the same variation across visits for Cross-device experimentation. | true |
| cbs (opcional) | bool | If true, Contextual Bandit score data will be retrieved. | false |
| personalization (opcional) | bool | If true, personalization data will be retrieved. This is required for the personalization condition. | false |
getVisitorWarehouseAudience()
Este método recupera all audience data associated with the visitor in your data warehouse using the specified visitorCode and warehouseKey. The warehouseKey is typically your internal user ID. The customDataIndex parameter corresponds to the Kameleoon custom data that Kameleoon uses to target your visitors. You can refer to the warehouse targeting documentation for additional details. The method passes the result to the returned future as a CustomData object, confirming that the data has been added to the visitor and is available for targeting purposes.
$warehouseAudienceCustomData = $kameleoonClient->getVisitorWarehouseAudience($visitorCode, $customDataIndex);
// If you need to specify warehouse key
$warehouseAudienceCustomData = $kameleoonClient->getVisitorWarehouseAudience(
$visitorCode, $customDataIndex, $warehouseKeyValue
);
// If you need to specify warehouse key & timeout
$warehouseAudienceCustomData = $kameleoonClient->getVisitorWarehouseAudience(
$visitorCode, $customDataIndex, $warehouseKeyValue, 2000
);
Argumentos
| Nombre | Tipo | Descripción |
|---|
| visitorCode | string | The unique identifier of the visitor for whom you want to retrieve and add the data. |
| customDataIndex | int | Entero que representa el índice del dato personalizado que desea utilizar para segmentar sus BigQuery Audiences. |
| warehouseKey | string | The unique key to identify the warehouse data (usually, your internal user ID). Este campo es opcional. |
| timeout | ?int | Timeout (in milliseconds). This parameter specifies the maximum amount of time the method can block to wait for a result. Este campo es opcional. If a timeout value is not provided, the SDK uses the default_timeout specified in your configuration. |
Valor de retorno
| Tipo | Descripción |
|---|
?Customdata | CustomData instance confirming that the data has been added to the visitor. If value is null, the request is failed and CustomData wasn’t added to the visitor. |
Excepciones lanzadas
| Type | Description |
|---|
VisitorCodeInvalid | Excepción que indica que el visitor code proporcionado no es válido (está vacío o tiene más de 255 caracteres). |
setLegalConsent()
You must use this method to specify whether the visitor has given legal consent to use thier personal data. Setting the legalConsent parameter to false limits the types of data that you can include in tracking requests. This method helps you adhere to legal and regulatory requirements while responsibly managing visitor data. You can find more information on personal data in the consent management policy.
$visitorCode = $kameleoonClient->getVisitorCode();
$kameleoonClient->setLegalConsent($visitorCode, true);
Argumentos
| Nombre | Tipo | Descripción |
|---|
| visitorCode | string | Identificador único del usuario. Este campo es obligatorio. |
| legalConsent | bool | Valor booleano que representa el estado del consentimiento legal. true indicates the visitor has given legal consent, false indicates the visitor has never provided, or has withdrawn, legal consent. Este campo es obligatorio. |
Excepciones lanzadas
| Type | Description |
|---|
| VisitorCodeInvalid | Exception indicating that the provided visitor code is not valid (empty, or longer than 255 characters). |
Comportamiento al revocar el consentimiento
Cuando llama a setLegalConsent() con legalConsent=false, el SDK no elimina la cookie kameleoonVisitorCode. En su lugar, deja de prorrogar la fecha de expiración de la cookie, permitiendo que esta persista hasta que expire de forma natural.
Si sus requisitos de cumplimiento exigen la eliminación inmediata del archivo de cookie al revocar el consentimiento, debe eliminarlo manualmente utilizando los métodos nativos de gestión de cookies de su framework. El SDK no eliminará el archivo automáticamente.
Goals and third party analytics
getEngineTrackingCode()
Kameleoon integrates with several analytics solutions, including Mixpanel, Google Analytics 4, and Segment. To track server-side experiments correctly, call the getEngineTrackingCode() method after the visitor triggers an experiment. The SDK returns JavaScript queue commands for the experiments that the visitor triggered during the previous five seconds. When you insert this code into the page, Engine.js processes the commands and sends the exposure events through the active analytics integration.
Consulte experimentación híbrida para más información sobre cómo implementar este método.
$engineTrackingCode = $kameleoonClient->getEngineTrackingCode($visitorCode);
- To use this feature, implement both the PHP SDK and Kameleoon Engine.js. Because Engine.js is used only for tracking in this flow, you can install the asynchronous tag before the closing
</body> tag.
- If you only want to track experiments in Kameleoon and do not need to send exposure events to third-party analytics tools, use the JavaScript / TypeScript SDK. This option works well for serverless edge compute platforms. The JavaScript / TypeScript SDK automatically tracks variations when you call
getVisitorCode, as long as you add the corresponding experiment assignments to window.kameleoonQueue..
- You can insert the returned tracking code directly into an HTML
<script> tag.
<html lang="en">
<body>
<script>
const engineTrackingCode = `
window.kameleoonQueue = window.kameleoonQueue || [];
window.kameleoonQueue.push(['Experiments.assignVariation', 123456, 7890, true]);
window.kameleoonQueue.push(['Experiments.trigger', 123456, true]);
window.kameleoonQueue.push(['Experiments.assignVariation', 234567, 8901, true]);
window.kameleoonQueue.push(['Experiments.trigger', 234567, true]);
`;
const script = document.createElement('script');
script.textContent = engineTrackingCode;
document.body.appendChild(script);
</script>
</body>
</html>
En este ejemplo, 123456 y 234567 son IDs de experimento, y 7890 y 8901 son IDs de variación. En su implementación, el SDK genera estos valores en el código de seguimiento devuelto.
Argumentos
| Nombre | Tipo | Descripción |
|---|
| visitorCode (obligatorio) | string | Identificador único del visitante. |
Valor de retorno
| Tipo | Descripción |
|---|
string | Código JavaScript para insertar en la página. |
trackConversion()
- 📨 Envía datos de seguimiento a Kameleoon
Use este método para track a conversion for a specific goal and user. This method requires visitorCode and goalId. In addition, this method also accepts an optional revenue, negative and metadata arguments. The visitorCode is usually identical to the one that was used when triggering the experiment.
El método trackConversion() no devuelve ningún valor. Este método no es bloqueante, ya que la llamada al servidor se realiza de forma asíncrona.
El parámetro isUniqueIdentifier está obsoleto. Utilice en su lugar UniqueIdentifier.isUniqueIdentifier también puede ser útil en otros escenarios excepcionales, como cuando no puede acceder al visitorCode anónimo asignado originalmente al visitante, pero sí tiene acceso a un ID interno conectado al visitante anónimo mediante la fusión de sesiones.
require "vendor/autoload.php";
$kameleoonClient = Kameleoon\KameleoonClientFactory::create("a8st4f59bj", "/tmp/kameleoon/client-php.json");
$visitorCode = $kameleoonClient->getVisitorCode();
$goalID = 83023;
$kameleoonClient->trackConversion($visitorCode, $goalID);
// if you operate with unique ID
$kameleoonClient->addData($visitorCode, new Kameleoon\Data\UniqueIdentifier(true));
$kameleoonClient->trackConversion($visitorCode, $goalID, 0.0);
// Add metadata
$cd = new Kameleoon\Data\CustomData(1, "metadata");
$kameleoonClient->trackConversion($visitorCode, $goalID, 0.0, null, null, false, [$cd]);
Argumentos
| Nombre | Tipo | Descripción | Default |
|---|
| visitorCode (obligatorio) | string | Identificador único del visitante. | |
| goalId (obligatorio) | int | ID del objetivo. | |
| revenue (opcional) | float | Ingreso de la conversión. | 0 |
| negative (opcional) | bool | Define si el ingreso es positivo o negativo. | false |
| metadata (opcional) | ?array<CustomData> | Le permite establecer valores específicos para los datos personalizados que se hayan definido como metadatos del objetivo en la aplicación de Kameleoon. Example: [CustomData{id: 5, value: "Payment Type"}, CustomData{id: 6, value: "Delivery Method"}]. In this example, 5 and 9 are the indexes of the custom data (5 = “Payment Type”, 9 = “Delivery Method”). | null |
| isUniqueIdentifier (deprecated) | bool | Parámetro opcional para indicar si el visitorCode es un identificador único. | false |
metadata values are accessible through raw data exports and the results page.Si se proporciona el parámetro metadata, Kameleoon utilizará estos valores especificados para la conversión actual en lugar de lo recopilado previamente mediante el método addData(). Si se omite el parámetro, Kameleoon utilizará los últimos valores rastreados para esos CustomData antes de la conversión y dentro de la misma visita.Kameleoon will only consider the metadata values that are explicitly passed as parameters to the trackConversion() method.En el siguiente ejemplo, Kameleoon will associate the conversion only with the custom data value explicitly provided as a parameter (here: index 5 with the value ‘Amex Credit Card’).$kameleoonClient->addData(
$visitorCode,
new CustomData(5, "Credit Card"),
new CustomData(9, "Express Delivery")
);
$kameleoonClient->trackConversion($visitorCode, 10, 0.0, null, null, false, [new CustomData(5, "Amex Credit Card")]);
Excepciones
| Tipo | Descripción |
|---|
VisitorCodeInvalid | Excepción que indica que el visitor code proporcionado no es válido. It is either empty or longer than 255 characters. |
Tipos de datos
Puede utilizar los siguientes tipos de datos predefinidos de Kameleoon\Data.
Browser
El conjunto de datos Browser almacenado aquí puede utilizarse para filtrar los informes de experimentación y personalización por cualquier valor asociado a él.
| Nombre | Tipo | Descripción |
|---|
| browserType (obligatorio) | int | List of browsers: CHROME, INTERNET_EXPLORER, FIREFOX, SAFARI, OPERA, OTHER. |
| version (opcional) | float | Version of the browser, floating point number represents major and minor version of the browser |
$kameleoonClient->addData($visitorCode, new Kameleoon\Data\Browser(Kameleoon\Data\Browser::CHROME));
$kameleoonClient->addData($visitorCode, new Kameleoon\Data\Browser(Kameleoon\Data\Browser::CHROME, 10.0));
PageView
| Name | Type | Description | Default |
|---|
| url (obligatorio) | string | URL of the page viewed. Este campo es obligatorio. | |
| title (obligatorio) | ?string | Title of the page viewed. Este campo es obligatorio. | null |
| referrers (opcional) | ?array<int> | Referrers de las páginas vistas. Este campo es opcional. | null |
The index (ID) of the referrer is available in our Back-Office in the Acquisition channel configuration page. Be careful: this index starts at 0, so the first acquisition channel you create for a given site would have the ID 0, not 1.
$kameleoonClient->addData(
$visitorCode,
new Kameleoon\Data\PageView("https://url.com", "title", [3])
);
Conversion
El conjunto de datos Conversion almacenado aquí puede utilizarse para filtrar los informes de experimentación y personalización por cualquier objetivo asociado a él.
- Each visitor can have multiple
Conversion objects.
- You can find the
goalId in the Kameleoon app.
| Nombre | Tipo | Descripción | Default |
|---|
| goalId (obligatorio) | int | ID del objetivo. | |
| revenue (opcional) | float | Revenue of the conversion | 0 |
| negative (opcional) | bool | Define si el ingreso es positivo o negativo. | false |
| metadata (opcional) | ?array<CustomData> | Metadatos de la conversión. | null |
$kameleoonClient->addData($visitorCode, new Kameleoon\Data\Conversion(32, 10, false));
$cd = new Kameleoon\Data\CustomData(1, "metadata");
$kameleoonClient->addData($visitorCode, new Kameleoon\Data\Conversion(32, 0.0, false, [$cd]));
CustomData
CustomData allows any type of data to be easily associated with each visitor. It can then be used as a targeting condition in segments or as a filter/breakdown in experiment reports.
To learn more about custom data, please refer to this article.
| Nombre | Tipo | Descripción | Default |
|---|
| indexOrName (obligatorio) | int/string | Índice o nombre del dato personalizado. Either index or name must be provided to identify the data. | |
| values (obligatorio) | string... | Value(s) of the custom data to be stored. | |
| overwrite (opcional) | bool | Flag para controlar explícitamente cómo se almacenan los valores y cómo aparecen en los informes. See more | true |
-
Each visitor is allowed only one
CustomData for each unique index. Adding another CustomData with the same index will replace the existing one.
-
The custom data ‘index’ can be found in the Custom Data dashboard under the “INDEX” column.
-
To prevent the SDK from sending data with the selected index to Kameleoon servers for privacy reasons, enable the option: Use this data only locally for targeting purposes when creating custom data.
-
Adding a
CustomData instance created with a name when the SDK instance configuration is not up to date or the name is not registered, will result in the data being ignored.
$kameleoonClient->addData($visitorCode, new Kameleoon\Data\CustomData(1, "value"));
// With several values
$kameleoonClient->addData($visitorCode, new Kameleoon\Data\CustomData(1, "value1", "value2"));
// To set the 'overwrite' flag to false
$kameleoonClient->addData($visitorCode, Kameleoon\Data\CustomData::newWithOverwrite(1, false, "value"));
// To use a name instead of the index
$kameleoonClient->addData($visitorCode, new Kameleoon\Data\CustomData("my-custom-data", "value"));
// To use a name instead of the index
// and set the 'overwrite' flag to false
$kameleoonClient->addData($visitorCode, Kameleoon\Data\CustomData::newWithOverwrite("my-custom-data", false, "value"));
Device
| Nombre | Tipo | Descripción |
|---|
| type | int | List of devices: PHONE, TABLET, DESKTOP. Este campo es obligatorio. |
$kameleoonClient->addData($visitorCode, new Kameleoon\Data\Device(Kameleoon\Data\Device::PHONE));
UserAgent
Keep track of visitors’ user-agent information. Server-side experiments are more likely to be affected by bot traffic than client-side experiments. Kameleoon uses the IAB/ABC International Spiders and Bots List to tackle this issue and recognize known bots and spiders. Kameleoon also uses the UserAgent field to filter out bots and other unwanted traffic that might distort your conversion metrics. Para más detalles, consulte our help article on bot filtering.
Si utiliza bots internos, le sugerimos pasar el valor curl/8.0 del userAgent para excluirlos de nuestra analítica.
| Nombre | Tipo | Descripción |
|---|
| value | string | The User-Agent value that will be sent with tracking requests. Este campo es obligatorio. |
$kameleoonClient->addData($visitorCode, new Kameleoon\Data\UserAgent("TestUserAgent"));
UniqueIdentifier
Si no añade UniqueIdentifier para un visitante, se utiliza visitorCode como identificador único del visitante, lo cual es útil para la experimentación entre dispositivos. Cuando añade UniqueIdentifier para un visitante, el SDK vincula los datos vaciados con el visitante asociado al identificador especificado.
isUniqueIdentifier puede ser útil en situaciones particulares; por ejemplo, si no puede acceder al visitorCode anónimo asignado a un visitante, pero puede usar un ID interno vinculado a ese visitante a través de la fusión de sesiones.
| Nombre | Tipo | Descripción |
|---|
| value | bool | Parameter for specifying if the visitorCode is a unique identifier. Este campo es obligatorio. |
$kameleoonClient->addData($visitorCode, new Kameleoon\Data\UniqueIdentifier(true));
OperatingSystem
OperatingSystem contains information about the operating system on the visitor’s device.
| Nombre | Tipo | Descripción |
|---|
| type | int | List of operating systems: WINDOWS, MAC, IOS, LINUX, ANDROID and WINDOWS_PHONE. Este campo es obligatorio. |
Each visitor can only have one OperatingSystem. Adding a second OperatingSystem overwrites the first one.
$kameleoonClient->addData($visitorCode, new Kameleoon\Data\OperatingSystem(Kameleoon\Data\OperatingSystem::WINDOWS));
Cookie
Cookie contains information about the cookie stored on the visitor’s device.
| Nombre | Tipo | Descripción |
|---|
| cookies | array | Map de objetos string que consta de claves y valores de cookies. Este campo es obligatorio. |
Each visitor can only have one Cookie. Adding a second Cookie overwrites the first one.
$cookie = new Kameleoon\Data\Cookie([
"k1" => "v1",
"k2" => "v2",
]);
$kameleoonClient->addData($visitorCode, $cookie);
Geolocation
Geolocation contains the visitor’s geolocation details.
| Nombre | Tipo | Descripción |
|---|
| country (obligatorio) | string | The country of the visitor. |
| region (opcional) | ?string | The region of the visitor. |
| city (opcional) | ?string | The city of the visitor. |
| postalCode (opcional) | ?string | The postal code of the visitor. |
| latitude (opcional) | float | The latitude coordinate representing the location of the visitor. Coordinate number represents decimal degrees. |
| longitude (opcional) | float | The longitude coordinate representing the location of the visitor. Coordinate number represents decimal degrees. |
- Each visitor can have only one
Geolocation. Adding a second Geolocation overwrites the first one.
$kameleoonClient->addData($visitorCode, new Kameleoon\Data\Geolocation("France", "Île-de-France", "Paris"));
ApplicationVersion
ApplicationVersion represents the semantic version number of your application.
A visitor can have only one ApplicationVersion. Adding a second instance will overwrite the first one.
| Nombre | Tipo | Descripción |
|---|
| version (opcional) | string | The mobile application version. This field must follow semantic versioning. Accepted formats are major, major.minor, or major.minor.patch. |
$kameleoonClient->addData($visitorCode, new Kameleoon\Data\ApplicationVersion("10")); // major
$kameleoonClient->addData($visitorCode, new Kameleoon\Data\ApplicationVersion("10.20")); // major.minor
$kameleoonClient->addData($visitorCode, new Kameleoon\Data\ApplicationVersion("10.20.30")); // major.minor.patch
Returned Types
DataFile
El DataFile contiene los detalles de configuración del SDK.
It can be extended with additional information if required by clients. If you need more details, please contact your Customer Success Manager.
| Nombre | Tipo | Descripción |
|---|
| featureFlags | array<string, FeatureFlag> | A map of FeatureFlag objects, keyed by feature flag keys. |
| dateModified | int | The timestamp (in milliseconds) indicating when the DataFile was last modified. |
// Retrieves the array of feature flags from the DataFile.
// The array is keyed by feature flag identifiers, with each value being a FeatureFlag object.
$featureFlags = $dataFile->featureFlags;
// Retrieves the last modification timestamp of the DataFile.
// The value is an int representing milliseconds since the Unix epoch.
$dateModified = $dataFile->getDateModified();
FeatureFlag
FeatureFlag representa un conjunto de propiedades que definen un feature flag en sí — por ejemplo, sus Variations, Rules, estado del entorno y otros detalles relacionados.
It can be extended with additional information if required by clients. If you need more details, please contact your Customer Success Manager.
| Nombre | Tipo | Descripción |
|---|
| isEnvironmentEnabled | bool | Indica si el feature flag está habilitado en el entorno actual. |
| defaultVariationKey | string | The key of the default variation associated with the feature flag. |
| variations | array<string, Variation> | A map of Variation objects, keyed by variation keys. |
| rules | array<Rule> | A list of Rule objects |
// Check whether the feature flag is enabled in the current environment
$isEnvironmentEnabled = $featureFlag->isEnvironmentEnabled;
// Retrieve the key of the default variation
$defaultVariationKey = $featureFlag->defaultVariationKey;
// Retrieve the default variation object
$defaultVariation = $featureFlag->getDefaultVariation();
// Retrieve all variations of the feature flag as a map (key = variation key, value = Variation object)
$variations = $featureFlag->variations;
// Retrieve all targeting rules associated with the feature flag
$rules = $featureFlag->rules;
Rule
Rule representa un conjunto de propiedades que definen una regla en sí — por ejemplo, sus Variations.
It can be extended with additional information if required by clients. If you need more details, please contact your Customer Success Manager.
| Nombre | Tipo | Descripción |
|---|
| variations | array<string, Variation> | A map of Variation objects, keyed by variation keys. |
// Retrieve all variations of the rule as a map (key = variation key, value = Variation object)
$variations = $rule->variations;
Variation
Variation contains information about the assigned variation to the visitor (or the default variation if no specific assignment exists).
| Nombre | Tipo | Descripción |
|---|
| name | string | The name of the variation. |
| key | string | The unique key identifying the variation. |
| id | ?int | The ID of the assigned variation (or null if it’s the default variation). |
| experimentId | ?int | The ID of the experiment associated with the variation (or null if default). |
| variables | array<string, Variable> | An array containing the variables of the assigned variation, keyed by variable names. This could be an empty collection if no variables are associated. |
- The
Variation object provides details about the assigned variation and its associated experiment, while the Variable object contains specific details about each variable within a variation.
- Ensure that your code handles the case where
id or experimentId may be null, indicating a default variation.
- The
variables array might be empty if no variables are associated with the variation.
// Retrieving the variation name
$variationName = $variation->name;
// Retrieving the variation key
$variationKey = $variation->key;
// Retrieving the variation id
$variationId = $variation->id;
// Retrieving the experiment id
$experimentId = $variation->experimentId;
// Retrieving the variables map
$variables = $variation->variables;
Variable
Variable contains information about a variable associated with the assigned variation.
| Nombre | Tipo | Descripción |
|---|
| key | string | The unique key identifying the variable. |
| type | string | The type of the variable. Possible values: BOOLEAN, NUMBER, STRING, JSON, JS, CSS |
| value | ?mixed | The value of the variable, which can be of the following types: bool, int, float, string, stdClass, array, null. |
// Retrieving the variables map
$variables = $variation->variables;
// Variable type can be retrieved for further processing
$type = $variables["isDiscount"]->type;
// Retrieving the variable value by key
$isDiscount = (bool) $variables["isDiscount"]->value;
// Variable value can be of different types
$title = (string) $variables["title"]->value;
Deprecated methods
Estos métodos están obsoletos y se eliminarán en la versión 5.0.0 del SDK.
getFeatureVariationKey()
- 📨 Envía datos de seguimiento a Kameleoon
To get feature variation key, call the getFeatureVariationKey() method of our SDK.
Este método toma un visitorCode and featureKey as mandatory arguments to get the variation key for a given user.
If a user has never been associated with this feature flag, the SDK returns a variation key randomly (according to the feature flag rules). If a user with a given visitorCode is already registered with this feature flag, it will detect the previous variation key value. If the user does not match any of the rules, the default value will be returned, which we can define in your customer’s account.
You have to make sure that proper error handling is set up in your code como se muestra en el ejemplo to the right to catch potential exceptions.
Si especifica un visitorCode, el método getFeatureVariationKey() lo usa como identificador único del visitante, lo cual es útil para la experimentación entre dispositivos. Cuando especifica un visitorCode y establece el parámetro isUniqueIdentifier en true, el SDK vincula los datos vaciados con el visitante asociado al identificador especificado.
El parámetro isUniqueIdentifier está obsoleto. Utilice en su lugar UniqueIdentifier.isUniqueIdentifier también puede ser útil en otros escenarios excepcionales, como cuando no puede acceder al visitorCode anónimo asignado originalmente al visitante, pero sí tiene acceso a un ID interno conectado al visitante anónimo mediante la fusión de sesiones.
$visitorCode = $kameleoonClient->getVisitorCode();
$featureKey = "featureKey";
$variationKey = "";
try {
$variationKey = $kameleoonClient->getFeatureVariationKey($visitorCode, $featureKey);
switch ($variationKey) {
case "on":
// Main variation key is selected for visitorCode
break;
case "alternativeVariation":
// Alternative variation key
break;
default:
// Default variation key
break;
}
} catch (Kameleoon\Exception\FeatureNotFound $e) {
// Feature toggle not yet activated on Kameleoon's side - we consider the feature inactive.
} catch (Kameleoon\Exception\DataFileInvalid $e) {
// It appears that the configuration has not been loaded
// and there is no previously saved version of the configuration available.
} catch (Kameleoon\Exception\VisitorCodeInvalid $e) {
// VisitorCode, which you passed to a method, is invalid and can't be accepted.
} catch (Kameleoon\Exception\FeatureEnvironmentDisabled){
// The feature flag is disabled for the environment.
} catch (Exception $e) {
// This is a generic Exception handler which will handle all exceptions.
echo "Exception: ", $e->getMessage(), "\n";
}
Argumentos
| Nombre | Tipo | Descripción |
|---|
| visitorCode | string | Identificador único del usuario. Este campo es obligatorio. |
| featureKey | string | Clave de la funcionalidad que desea exponer a un usuario. Este campo es obligatorio. |
| timeout | ?int | Timeout (in milliseconds). This parameter specifies the maximum amount of time the method can block to wait for a result. Este campo es opcional. If a timeout value is not provided, the SDK uses the default_timeout specified in your configuration. |
| isUniqueIdentifier (Obsoleto) | ?bool | Parámetro opcional para indicar si el visitorCode es un identificador único. If not provided, el valor predeterminado es null. The field is optional. |
Valor de retorno
| Tipo | Descripción |
|---|
| string | Variation key of the feature flag that is registered for a given visitorCode. |
Excepciones lanzadas
| Tipo | Descripción |
|---|
| FeatureNotFound | Exception indicating that the requested feature ID has not been found in the internal configuration of the SDK. This is usually normal and means that the feature flag has not yet been activated on Kameleoon’s side (but code implementing the feature is already deployed on the web-application’s side). |
| FeatureEnvironmentDisabled | Excepción que indica que el feature flag está deshabilitado para el entorno actual del visitante (por ejemplo, production, staging o development). |
| VisitorCodeInvalid | Exception indicating that the provided visitor code is not valid (empty, or longer than 255 characters). |
| DataFileInvalid | Exception indicating that the configuration has not been loaded and there is no previously saved version of the configuration available. |
getActiveFeatureListForVisitor()
Este método toma only input parameters: visitorCode. Result contains only active feature flags for a given visitor.
$visitorCode = "visitor";
$arrayFeatureFlagKeys = $kameleoonClient->getActiveFeatureListForVisitor($visitorCode);
Argumentos
| Name | Type | Description |
|---|
| visitorCode | string | Identificador único del usuario. Este campo es obligatorio. |
| timeout | ?int | Timeout (in milliseconds). This parameter specifies the maximum amount of time the method can block to wait for a result. Este campo es opcional. If a timeout value is not provided, the SDK uses the default_timeout specified in your configuration. |
Valor de retorno
| Type | Description |
|---|
| any | List of feature flag keys which are active for a given visitorCode |
Excepciones lanzadas
| Type | Description |
|---|
| VisitorCodeInvalid | Exception indicating that the provided visitor code is not valid (empty, or longer than 255 characters). |
| DataFileInvalid | Exception indicating that the configuration has not been loaded and there is no previously saved version of the configuration available. |
getActiveFeatures()
getActiveFeatures method retrieves information about the active feature flags that are available for the specified visitor code.
$visitorCode = "visitor";
$arrayActiveFeatures = $kameleoonClient->getActiveFeatures($visitorCode);
Argumentos
| Nombre | Tipo | Descripción |
|---|
| visitorCode | string | Identificador único del usuario. Este campo es obligatorio. |
| timeout | ?int | Timeout (in milliseconds). This parameter specifies the maximum amount of time the method can block to wait for a result. Este campo es opcional. If a timeout value is not provided, the SDK uses the default_timeout specified in your configuration. |
Valor de retorno
| Tipo | Descripción |
|---|
| array | An array that contains the assigned variations of the active features using the active feature IDs as keys. |
Excepciones lanzadas
| Tipo | Descripción |
|---|
| VisitorCodeInvalid | Exception indicating that the provided visitor code is not valid (empty, or longer than 255 characters). |
| DataFileInvalid | Exception indicating that the configuration has not been loaded and there is no previously saved version of the configuration available. |
getFeatureVariable()
- 📨 Envía datos de seguimiento a Kameleoon
- Use
getVariation() instead.
- This method was previously called
obtainFeatureVariable, which has been deprecated since SDK version 3.0.0 and will be removed in a future release.
To get the variable of a variation key associated with a user, call the getFeatureVariable() method.
Este método toma un visitorCode, featureKey, and variableName as mandatory arguments to get a variable of the variation key for a given user.
If the user has never been associated with this feature flag, the SDK returns a variable value of the variation key randomly (according to the feature flag rules). If a user with a given visitorCode is already registered with this feature flag, the method will detect the variable value for the associated variation. If the user does not match any of the rules, the default variable will be returned.
Ensure proper error handling is set up in your code como se muestra en el ejemplo to the right to catch potential exceptions.
Si especifica un visitorCode, el método getFeatureVariable() lo usa como identificador único del visitante, lo cual es útil para la experimentación entre dispositivos. Cuando especifica un visitorCode y establece el parámetro isUniqueIdentifier en true, el SDK vincula los datos vaciados con el visitante asociado al identificador especificado.
El parámetro isUniqueIdentifier está obsoleto. Utilice en su lugar UniqueIdentifier.isUniqueIdentifier es útil en otros escenarios excepcionales, como cuando no puede acceder al visitorCode anónimo asignado originalmente al visitante, pero sí tiene acceso a un ID interno conectado al visitante anónimo mediante la fusión de sesiones.
$visitorCode = $kameleoonClient->getVisitorCode();
$featureKey = "featureKey";
$variableName = "variableName";
try {
$variationValue = $kameleoonClient->getFeatureVariable($visitorCode, $featureKey, $variableName);
// Your custom code depending of variableValue
} catch (Kameleoon\Exception\FeatureNotFound $e) {
// Feature toggle not yet activated on Kameleoon's side - we consider the feature inactive.
} catch (Kameleoon\Exception\FeatureEnvironmentDisabled){
// The feature flag is disabled for the environment.
} catch (Kameleoon\Exception\VisitorCodeInvalid $e) {
// VisitorCode, which you passed to a method, is invalid and can't be accepted.
} catch (Kameleoon\Exception\FeatureVariableNotFound $e) {
// Requested variable not defined on Kameleoon's side.
} catch (Kameleoon\Exception\DataFileInvalid $e) {
// It appears that the configuration has not been loaded
// and there is no previously saved version of the configuration available.
} catch (Exception $e) {
// This is a generic Exception handler which will handle all exceptions.
echo "Exception: " . $e->getMessage() . "\n";
}
Argumentos
| Nombre | Tipo | Descripción |
|---|
| visitorCode | string | Identificador único del usuario. Este campo es obligatorio. |
| featureKey | string | Clave de la funcionalidad que desea exponer a un usuario. Este campo es obligatorio. |
| variableName | string | Name of the variable you want to get a value. Este campo es obligatorio. |
| timeout | ?int | Timeout (in milliseconds). This parameter specifies the maximum amount of time the method can block to wait for a result. Este campo es opcional. If a timeout value is not provided, the SDK uses the default_timeout specified in your configuration. |
| isUniqueIdentifier (Obsoleto) | ?bool | Parámetro opcional para indicar si el visitorCode es un identificador único. If not provided, el valor predeterminado es null. The field is optional. |
Valor de retorno
| Tipo | Descripción |
|---|
| Any | Value of variable of variation that is registered for a given visitorCode for this feature flag. Possible types: bool, int, float, string, object, array |
Excepciones lanzadas
| Tipo | Descripción |
|---|
| FeatureNotFound | Exception indicating that the requested feature ID has not been found in the internal configuration of the SDK. This is usually normal and means that the feature flag has not yet been activated on Kameleoon’s side (but code implementing the feature is already deployed on the web-application’s side). |
| FeatureEnvironmentDisabled | Excepción que indica que el feature flag está deshabilitado para el entorno actual del visitante (por ejemplo, production, staging o development). |
| VisitorCodeInvalid | Exception indicating that the provided visitor code is not valid (empty, or longer than 255 characters). |
| FeatureVariableNotFound | Exception indicating that the requested variable has not been found. Check that the variable’s ID (or key) matches your code. |
| DataFileInvalid | Exception indicating that the configuration has not been loaded and there is no previously saved version of the configuration available. |
getFeatureVariationVariables()
- Use
getVariation() instead.
- This method was previously called
getFeatureAllVariables, which was removed in SDK version 4.0.0.
To retrieve the all feature variables, call the getFeatureVariationVariables() method. A feature variable can be changed easily via our web application.
Este método toma featureKey and variationKey as mandatory arguments. It will return the data with the object type, as defined on the web interface. The method throws an error (FeatureNotFound) if the requested feature flag has not been found in the SDK’s client configuration. If the variation key isn’t found, the method throws the FeatureVariationNotFound error.
$featureKey = "test_feature_variables";
$variationKey = "on";
try {
$variables = $kameleoonClient->getFeatureVariationVariables($featureKey, $variationKey);
$firstName = $variables["firstName"];
} catch (Kameleoon\Exception\FeatureNotFound $e) {
// The feature is not yet activated on Kameleoon's side.
} catch (Kameleoon\Exception\FeatureEnvironmentDisabled){
// The feature flag is disabled for the environment.
} catch (Kameleoon\Exception\FeatureVariationNotFound $e) {
// The variation is not yet activated on Kameleoon's side, i.e., the associated experiment is not online.
} catch (Kameleoon\Exception\DataFileInvalid $e) {
// It appears that the configuration has not been loaded
// and there is no previously saved version of the configuration available.
} catch (Exception $e) {
// This is a generic Exception handler which will handle all exceptions.
echo "Exception: " . $e->getMessage() . "\n";
}
Argumentos
| Nombre | Tipo | Descripción |
|---|
| featureKey | string | Key of the feature flag you want to obtain. Este campo es obligatorio. |
| variationKey | string | Clave de la variación que desea obtener. Este campo es obligatorio. |
| timeout | ?int | Timeout (in milliseconds). This parameter specifies the maximum amount of time the method can block to wait for a result. Este campo es opcional. If a timeout value is not provided, the SDK uses the default_timeout specified in your configuration. |
Valor de retorno
| Tipo | Descripción |
|---|
| Any | Value of the variation variable that is registered for a given visitorCode for this feature flag. Possible types: bool, int, float, string, object, array |
Excepciones lanzadas
| Tipo | Descripción |
|---|
| FeatureNotFound | Exception indicating that the requested feature ID has not been found in the SDK’s internal configuration. This is usually normal and means that the feature flag has not yet been activated on Kameleoon’s side (but code implementing the feature is already deployed on the web-application’s side). |
| FeatureEnvironmentDisabled | Excepción que indica que el feature flag está deshabilitado para el entorno actual del visitante (por ejemplo, production, staging o development). |
| FeatureVariationNotFound | Exception indicating that the requested variation ID has not been found in the SDK’s internal configuration. Esto suele ser normal y significa que el experimento correspondiente a la variación todavía no se ha activado del lado de Kameleoon. |
| DataFileInvalid | Exception indicating that the configuration has not been loaded and there is no previously saved version of the configuration available. |
getFeatureList()
Devuelve una lista de claves de feature flags disponibles actualmente en el SDK.
$arrayFeatureKeys = $kameleoonClient->getFeatureList();
Argumentos
| Nombre | Tipo | Descripción |
|---|
| timeout (opcional) | ?int | Timeout (in milliseconds). This parameter specifies the maximum amount of time the method can block to wait for a result. If a timeout value is not provided, the SDK uses the default_timeout specified in your configuration. |
Valor de retorno
| Tipo | Descripción |
|---|
array<string> | List of feature flag keys |