目录
此内容是否有帮助?

# PHP SDK User Guide

TIP

Before accessing, please read the preparation before accessing .

You can get the PHP SDK source code in GitHub (opens new window).

**The latest version is **: 1.8.0 .

**Update time is **: 2021- 11 -0 9

# I. Install SDK

  • You can get the source code of the SDK from GitHub (opens new window)and integrate it into your project. Just put the TaPhpS dk.php in the directory where your project is located. This SDK is compatible with PHP > 5.5, and some functions rely on curl extensions.
  • You can also use composer integration
{
    "require": {
        "thinkinggame/ta-php-sdk": "v1.8.0"
    }
}

# II. Initializate of SDK

Write the following code into the program to introduce the SDK:

<?php
require "TaPhpSdk.php";
?>

After introducing the SDK, you need to get the SDK instance

//Initialise SDK in two ways, Consumer includes the following(FileConsumer,BatchConsumer,DebugConsumer
//(1)defulte
$ta = ThinkingDataAnalytics(Consumer);
//(2)Add UUID for de dupulication
$enableUUID = true;
$ta = new ThinkingDataAnalytics(Consumer,$enableUUID);

You can get three different SDK instances. It is recommended to use FileConsumer:

**(1) FileConsumer: **batch real-time writing of local files, need to use with LogBus for data upload, **recommended use **, does not support multi-threading, generate an instance can be adjusted by passing parameters file cutting rules.

Initialize TA:

<?php
//Split files by day by default
$ta = new ThinkingDataAnalytics(new FileConsumer("/log_dir"));
?>

If you want to split the file by size, you can initialize it as follows:

<?php
//Set the size of the file cut in MB, here 1024MB, similar file name: log. Date_ Number (log.2020-01-03_0), which is the index for file segmentation
$ta = new ThinkingDataAnalytics(new FileConsumer("/log_dir", 1024));
?>

If you want to split the file by the hour, you can initialize it as follows:

<?php
//Divided by hour, the file name is similar: log. Date-hour_ numerical value(log.2019-09-12-15_0)
$ta = new ThinkingDataAnalytics(new FileConsumer("/log_dir", 0, true));
?>

If you need to set the generated log file prefix, you can initialize it as follows:

<?php
//Divided by hour, the file name is similar: a.log. Date-hour_ numerical value(log.2019-09-12-15_0)
$ta = new ThinkingDataAnalytics(new FileConsumer("/log_dir", 0, true,"a"));
?>

The first parameter passed in is to write to the local folder address. You only need to set the listening folder address of LogBus to the address here, and you can use LogBus to monitor and upload data. The second parameter is the cut size of the file. The default size is not limited, in MB. The third parameter sets whether to cut by the hour. The default is false, that is, it is not turned on.

**(2) BatchConsumer: **batch real-time transmission of data to the TA server, do not need to match the transmission tool, you can set the maximum amount of data uploaded each time (default 20) and cache the maximum batch (default 50 batches), that is, the default maximum cache data amount is 20 * 50. In the case of prolonged network outages, there is a risk of data loss.

<?php
$ta = new ThinkingDataAnalytics(new BatchConsumer("SERVER_URI","APP_ID"));
?>

If you want to transfer data to the intranet, you can initialize it as follows:

<?php
$batchConsumer = new BatchConsumer("SERVER_URI","APP_ID")
//Compression or not, default compression gzip, if intranet transmission, false is recommended
$batchConsumer -> setCompress(false);
$ta = new ThinkingDataAnalytics($batchConsumer);
?>

SERVER_URIFor the URL of the data transfer, APP_IDFor the APP ID of your project

If you are using Cloud as a Service, enter the following URL:

http://receiver.ta.thinkingdata.cn

If you are using the version of private deployment, enter the following URL:

http://Data Acquisition Address

Note: Enter the following URL before version 1.2.0:

http://receiver.ta.thinkingdata.cn/logagent
http://Data Acquisition Address/logagent

**(3) DebugConsumer: **Real-time transmission of data to the TA server one by one, no need to match the transmission tool. If the data is wrong, the entire data will not be put into storage, and a detailed error description will be returned. It is not recommended for use in a production environment. Multi-threading is not supported.

<?php
$ta = new ThinkingDataAnalytics(new DebugConsumer("SERVER_URI","APP_ID"));
?>

If you want **DebugConsumer **to only validate data and not write to the TA library, you can initialize it as follows:

<?php
$debugConsumer = new DebugConsumer("SERVER_URI","APP_ID");
//debugConsumer whether to write to TA library, true-write, false-not write. The default value is true
$debugConsumer->setDebugOnly(false);
$ta = new ThinkingDataAnalytics($debugConsumer);
?>

SERVER_URIURL for data transfer, APP_IDAPP ID for your project

If you are using Cloud as a Service, enter the following URL:

http://receiver.ta.thinkingdata.cn

If you are using the version of private deployment, enter the following URL:

http://Data Acquisition Address

# Three, send events

After the SDK initialization is completed, you can call trackto upload events. In general, you may need to upload more than a dozen to hundreds of different events. If you are using the TA background for the first time, we recommend You upload a few key events first.

# 3.1 Send Events

You can call trackto upload events. It is recommended that you set the attributes of the event and the conditions for sending information according to the previously combed doc. Here, take user payment as an example:

<?php
//Account ID of the user in login status
$account_id = "ABC12345";

//When a user is not logged in, a unique identifier such as the cookieId generated by the product itself can be used to identify the user
$distinct_id = "SDIF21dEJWsI232IdSJ232d2332";

$properties = array();

//Set the time for this data. If not, the default is the current time in the format"Y-m-d H:i:s"
$properties["#time"] = date("Y-m-d H:i:s",time());

//Set the client IP will automatically parse the location information based on the IP address
$properties["#ip"] = "123.123.123.123";

//Set other properties of the event
$properties["Product_Name"] ="product name";
$properties["Price"] = 30;
$properties["OrderId"] ="abc_123";

//The incoming parameters are visitor ID, account ID, event name and event attribute, respectively.
try{
  $ta->track($distinct_id,$account_id,"Payment",$properties);
}catch (Exception $e){
   //exception handling
    echo $e;
}

//You can upload only one ID, or any other interface in the SDK that requires an upload user ID can upload only one ID.
//try{
//$ta->track(null,$account_id,"Payment",$properties);
//$ta->track($distinct_id,null,"Payment",$properties);
//}catch (Exception $e){
//exception handling
//echo $e;
}

?>

**Note: **In order to ensure that the guest ID and account ID can be successfully bound, if your product will use the guest ID and account ID, we strongly recommend that you upload the two IDs at the same time, otherwise the account will not match, resulting in the user Double calculation, the specific ID binding rules can refer to the user identification rules chapter.

  • The name of the event can only start with a letter and can contain numbers, letters and an underscore "_". The maximum length is 50 characters and is not sensitive to letter case.
  • The attributes of an event are an associative array where each element represents an attribute.
  • The Key value of the array element is the name of the attribute and is of stringtype. It is stipulated that it can only start with letters, including numbers, letters and underscore "_". The maximum length is 50 characters and is not sensitive to letter case.
  • The value of the array element is the value of the attribute, supporting string, integer, float, boolean, DataTime, array

# 3.2 Set Public Event Properties

For some properties that need to appear in all events, you can call the register_public_propertiesto set the public event properties. We recommend that you set the public event properties before sending the event.

<?php
$public_properties = array();
$public_properties["server_version"] ="1.2.3";
$public_properties["server_name"] = "A1001";
$ta->register_public_properties($public_properties);
?>

After the register_public_propertiesis called and the public properties are set, all events uploaded afterwards will have these properties.

  • The public event attribute is also an associative array, where each element represents an attribute.
  • The Key value of the array element is the name of the attribute and is of stringtype. It is stipulated that it can only start with letters, including numbers, letters and underscore "_". The maximum length is 50 characters and is not sensitive to letter case.
  • The value of the array element is the value of the attribute, supporting string, integer, float, boolean, DataTime, array

If you call register_public_propertiesset a previously set public event property, the previous property value will be overwritten, whichever is the newly set public property. If the public event property and the Key of a property in the trackupload event duplicate, the property of the event overrides the public event property, that is, the property at the time of the upload event.

If you want to empty all public event properties, you can call clear_public_properties.

<?php
$ta->clear_public_properties();
?>

# IV. User Attributes

TA platform currently supports the user feature interface to user_set, user_setOnce, user_add, user_del.

# 4.1 user_set

For general user feature, you can call user_setto set it. The attributes uploaded using this interface will overwrite the original attribute values. If the user feature does not exist before, the user feature will be created and written. The attribute type is the same as the type when passed in:

<?php
$properties = array();

//Upload user property, create new property "user_name" with the value "ABC"
$properties["user_name"] = "ABC";
try{
  $ta->user_set($distinct_id,$account_id,$properties);
}catch (Exception $e){
   //exception handling
    echo $e;
}
//Upload the user property again, and the value of "user_name" will be overwritten with "XYZ"
$properties["user_name"] = "XYZ";
try{
  $ta->user_set($distinct_id,$account_id,$properties);
}catch (Exception $e){
   //exception handling
    echo $e;
}
?>
  • user_setThe user feature set is an associative array where each element represents an attribute.
  • The Key value of the array element is the name of the attribute and is of stringtype. It is stipulated that it can only start with letters, including numbers, letters and underscore "_". The maximum length is 50 characters and is not sensitive to letter case.
  • The value of the array element is the value of the attribute, support string, integer, float, boolean, DataTime, array

# 4.2 user_setOnce

If the user feature you want to upload only needs to be set once, you can call user_setOnceto set it. When the attribute already has a value before, this information will be ignored:

<?php
$properties = array();

//Similarly, upload the user property, create a new property "user_name" with the value "ABC"
$properties["user_name"] = "ABC";
try{
  $ta->user_setOnce($distinct_id,$account_id,$properties);
}catch (Exception $e){
   //exception handling
    echo $e;
}

//Upload the user property again, when the value "user_name" already exists, so it is still "ABC" without modification; The value of "user_age" is 18
$properties["user_name"] = "XYZ";
$properties["user_age"] = 18;
try{
  $ta->user_setOnce($distinct_id,$account_id,$properties);
}catch (Exception $e){
   //exception handling
    echo $e;
}
?>

user_setOnceThe user feature type and restrictions set are consistent with user_set.

# 4.3 user_add

When you want to upload a numeric attribute, you can call user_addto accumulate the attribute. If the attribute has not been set, a value of 0 will be assigned before calculation. Negative values can be passed in, which is equivalent to subtraction operations.

<?php

//Upload user attributes with total_revenue value of 30 and vip_level value of 1
$properties = array();
$properties["total_revenue"] = 30;
$properties["vip_level"] = 1;
try{
  $ta->user_add($distinct_id,$account_id,$properties);
}catch (Exception $e){
   //exception handling
    echo $e;
}

//Upload user attributes again, when the value of "total_revenue" is 90 and the value of "vip_level" is 1
$properties_other = array();
$properties_other["total_revenue"] = 60;
try{
  $ta->user_add($distinct_id,$account_id,$properties_other);
}catch (Exception $e){
   //exception handling
    echo $e;
}
?>

user_addThe user feature type and restrictions set are the same as user_set, but only valid for numeric user features.

# 4.4 user_append

When you want to append the user feature value to the array type, you can call user_appendto append the specified attribute, if the attribute has not been created in the cluster, then user_appendcreates the attribute

<?php
//user_append add one or more sets of users
try{
    $properties = array();
    $properties['arr'] = ['str3','str4'];//Add multiple values to the set type, in the form of key-arrays, which are all string types
    $ta->user_append($distinct_id, $account_id, $properties);
}catch (Exception $e){
    //handle except
    echo $e;
}
?>

# 4.5 user _ del

If you want to delete a user, you can call user_delto delete the user. You will no longer be able to query the user features of the user, but the events generated by the user can still be queried.

<?php
try{
  $ta->user_del($distinct_id,$account_id);
}catch (Exception $e){
   //exception handling
    echo $e;
}
?>

# 4.6 user_unset

When you want to empty the user feature value of the user, you can call user_unsetto empty the specified attribute. If the attribute has not been created in the cluster, user_unsetwill not create the attribute.

<?php
$properties = array(
    'user_age', "vip_level"
);
try{
 $ta->user_unset($distinct_id,$account_id, $properties);
}catch (Exception $e){
   //exception handling
    echo $e;
}
?>

# V. Other Operations

# 5.1 Submit Data Immediately

<?php
$ta->flush();
?>

Submit data to the appropriate receiver immediately.

# 5.2 Close sdk

<?php
try{
  $ta->close();
}catch (Exception $e){
   //exception handling
  echo $e;
}
?>

Close and exit sdk, please call this interface before shutting down the server to avoid data loss in the cache**.**

# VI. Relevant Preset Attributes

# 6.1 Preset Properties for All Events

The following preset properties are included with all events in the PHP SDK, including AutoCollect events.

Attribute name
Chinese name
Description
#ip
IP address
The user's IP address needs to be manually set, and TA will use this to obtain the user's geographic location information
#country
Country
User's country, generated according to IP address
#country_code
Country code
The country code of the country where the user is located (ISO 3166-1 alpha-2, that is, two uppercase English letters), generated based on the IP address
#province
Province
The user's province is generated according to the IP address
#city
City
The user's city is generated according to the IP address
# lib
SDK type
The type of SDK you access, such as PHP, etc
#lib_version
SDK version
The version you access to the PHP SDK

# VII. Other Functions

# 7.1 Specify File Prefixes

Starting from v1.5.0, FileConsumer of the SDK supports specifying the generated file prefix, and the specified directory will be automatically created when it does not exist. The usage method is as follows:

<?php
// The last parameter is the specified file prefix and the generated file name is:test.log.2020-12-07
$debugConsumer = new FileConsumer("/Users/sunzeyu/Work/test/test/", 0, false, "test");
$ta = new ThinkingDataAnalytics($debugConsumer);
?>

# VIII. Advanced Functions

Starting from v1.4.0, the SDK supports the reporting of two special types of events: updatable events and rewritable events. These two events need to be used in conjunction with TA system 2.8 and later versions. Since special events are only applicable in certain specific scenarios, please use special events to report data with the help of Count Technology's customer success and analysts.

# 8.1 Updatable Events

You can implement the need to modify event data in a specific scenario through updatable events. Updatable events need to specify an ID that identifies the event and pass it in when the updatable event object is created. The TA background will determine the data that needs to be updated based on the event name and event ID.

$account_id = "2121";
$distinct_id = "SJ232d233243";
try{
// Instance: Report an event that can be updated, assuming the event name is UPDATABLE_ EVENT
$event_name = "UPDATABLE_EVENT";
$event_id = "test_event_id";
$properties = array();
$properties['price'] = 100;
$properties['status'] = 3;
// Event attributes after reporting are status 3 and price 100
$ta->track_update($distinct_id, $account_id,$event_name, $event_id,$properties);

$protertiesNew = array();
$protertiesNew['status'] = 5;
// Same $event_after reporting Name + $event_ The event attribute status of ID is updated to 5, price remains unchanged
$ta->track_update($distinct_id, $account_id, $event_name, $event_id, $protertiesNew);

$ta->flush();
}catch (Exception $e){
    //handle exception
    echo $e;
}

# 8.2 Rewritable Events

Rewritable events are similar to updatable events, except that rewritable events will completely cover historical data with the latest data, which is equivalent to deleting the previous data and storing the latest data in effect. The TA background will determine the data that needs to be updated based on the event name and event ID.

$account_id = "2121";
$distinct_id = "SJ232d233243";
try{
// Instance: Report an event that can be rewritten, assuming that the event name is overwrite_ EVENT
$event_name = "OVERWRITE_EVENT";
$event_id = "test_event_id";
$properties = array();
$properties['price'] = 100;
$properties['status'] = 3;
// After reporting, the event attribute status is 3 and the price is 100
$ta->track_overwrite($distinct_id, $account_id,$event_name, $event_id,$properties);

$protertiesNew = array();
$protertiesNew['status'] = 5;
// Same $event after reporting_ name + $event_ After the event attribute of ID is reported, the event attribute status is updated to 5 and the price attribute is deleted
$ta->track_overwrite($distinct_id, $account_id, $event_name, $event_id, $protertiesNew);

$ta->flush();
}catch (Exception $e){
    //handle exception
    echo $e;
}

# ChangeLog

# v1.8.0 (2021/11/09)

  • Added support for complex structure types

# v1.7.0 (2021/06/01)

  • Fix public property override bug
  • Fix the problem that the user_del () method cannot be called

# v1.6.0 (2021/03/12)

  • BatchConsumer adds upload failure cache

# v1.5.0 (2020/12/07)

  • LoggerConsumer adds automatically created when the specified directory does not exist
  • LoggerConsumer adds file lock configuration
  • LoggerConsumer adds the specified build file prefix

# v1.4.0 (2020/08/27)

  • Added track_update interface to support updatable events
  • Added track_overwrite interface to support rewritable events
  • Added UUID initialization method

# v1.3.0 (2020/02/10)

  • Supports array types
  • Added user_append interface to support attribute appending of user's array type

# v1.2.1 (2020/01/15)

  • Fix incorrect format when v1.1.1 #time accurate milliseconds

# v1.2.0 (2020/01/03)

  • Added user_unset interface to delete user features
  • LoggerConsumer optimization: increase stability, remove the default file size 1G upper limit. Users can configure their own segmentation by day, hour, and size
  • DebugConsumer Optimization: More complete and accurate validation of data at the server level
  • BatchConsumer performance optimization: support for configuring compression mode; remove Base64 encoding

# v1.1.1 (2019/12/05)

  • Support #time accurate to milliseconds

# v1.1.0 (2019/09/12)

  • Supporting DebugConsumer
  • Support log file segmentation by hour

# v1.0.4 (2019/09/04)

  • Fix BatchConsumer's error return code
  • Add BatchConsumer destructor

# v1.0.3 (2019/08/30)

  • Add the function of splitting files by file size.