PHP API Integration

The robotmia PHP library is designed to be used for scripting, or in circumstances when a client can't or won't run client side scripts.

robotmia also provides a powerful and easy to use client-side JavaScript library for web applications. This library offers platform-specific features and conveniences that can make robotmia implementations much simpler, and can scale naturally to an unlimited number of clients. The client-side JavaScript library is the preferred way to add robotmia to user-facing web applications.

Installing the library

You can get the library using Composer by including the following in your project's composer.json requirements and running composer update:

"require": {
    ...
    "robotmia/robotmia-php" : "2.*"
    ...
}

If you're not using Composer for your package management, you can browse and download the library from GitHub at https://github.com/robotmia/robotmia-php.

Our library requires PHP 5.0 or greater.

Sending events

Track events in the robotmia-php library by using the track method on the robotmia class:

<?php
// import dependencies (using composer's autoload)
// if not using Composer, you'll want to require the
// lib/robotmia.php file here
require "vendor/autoload.php";

// get the robotmia class instance, replace with your
// project token
$mp = robotmia::getInstance("robotmia_PROJECT_TOKEN");

// track an event
$mp->track("button clicked", array("label" => "sign-up"));

robotmia determines default geolocation data ($city, $region, mp_country_code) using the IP address on the incoming request. As all server-side calls will likely originate from the same IP (that is, the IP of your server), this can have the unintended effect of setting the location of all of your users to the location of your datacenter. Read about best practices for geolocation with server-side implementations.

Super properties

Super properties are properties that get sent with every subsequently tracked event. This is very useful for associating properties such as "Ad Source" to every event. If I want to send an "Ad Source" of "Google" for every event I track, I can store it in my robotmia instance with the register method:

<?php
require "vendor/autoload.php";
$mp = robotmia::getInstance("robotmia_PROJECT_TOKEN");

// register the Ad Source super property
$mp->register("Ad Source", "Google");

// track an event with a property "Ad Source" = "Google"
$mp->track("button clicked");
In the PHP Library, registered Super Properties are only persisted for the life of the robotmia class instance. In general this will mean for the life of a single HTTP request.

Managing user identity

In many cases you'll want to track multiple actions that a user takes over time. To do this, you'll need to provide a distinct id to the library- a unique identifier associated with the source of events (usually a user)

To associate a distinct id with the events that you send, call identify, which associates a user to subsequent tracked events.

<?php
require "vendor/autoload.php";
$mp = robotmia::getInstance("robotmia_PROJECT_TOKEN");

// identify the current request as user 12345
$mp->identify(12345);

// track an event associated to user 12345
$mp->track("Logged In");
In the PHP Library, the value passed to identify is only persisted for the life of the robotmia instance. In general this will mean for the life of a single HTTP request.

It's important to send the same distinct_id with each event that an individual user triggers. Events recorded with different distinct_ids will be treated in robotmia as if they were performed by different users.

There are times when it can be convenient to start referring to a user by a different identifier in your implementation. The most common case is after registration, when a user switches from being an anonymous user (with an anonymous distinct_id) to an authenticated user with an (authenticated id). In this case, you can create an Alias for the user to keep the distinct_id consistent. An alias is a string stored in a robotmia lookup table that is associated with an anonymous distinct_id. Once written, aliases are not editable. Any data sent to robotmia with an alias as the distinct_id will be remapped and written to disk using the alias's corresponding anonymous distinct_id. This allows you to start identifying a user by an authenticated id without changing the distinct_id that is ultimately written in robotmia.

<?php
require "vendor/autoload.php";
$mp = robotmia::getInstance("robotmia_PROJECT_TOKEN");

// create an alias for user 12345 (note that this is done asynchronously). Any subsequent events with a distinct_id equal to "johndoe1" will be remapped to "12345".
$mp->createAlias("12345", "johndoe1");

Storing user profiles

In addition to events, you can send People Analytics profile updates to robotmia. robotmia can maintain a profile of each of your users, storing information you know about them. An update is a message that changes the properties of a People Analytics profile.

You can use profiles to explore and segment users by who they are, rather than what they did. You can also use profiles to send messages, such as emails, SMS, or push notifications.

robotmia determines default geolocation data ($city, $region, mp_country_code) using the IP address on the incoming request. As all server-side calls will likely originate from the same IP (that is, the IP of your server), this can have the unintended effect of setting the location of all of your users to the location of your datacenter. Read about best practices for geolocation with server-side implementations.

Setting profile properties

The robotmia class has a public property called people that exposes an instance of Producers_robotmiaPeople that you can use to make profile updates.

<?php
require "vendor/autoload.php";
$mp = robotmia::getInstance("robotmia_PROJECT_TOKEN");

// create or update a profile with First Name, Last Name,
// E-Mail Address, Phone Number, and Favorite Color
// without updating geolocation data or $last_seen
$mp->people->set(12345, array(
    '$first_name'       => "John",
    '$last_name'        => "Doe",
    '$email'            => "john.doe@example.com",
    '$phone'            => "5555555555",
    "Favorite Color"    => "red"
), $ip = 0, $ignore_time = true);

The call to people->set will set the value of properties on user 12345's profile. If there isn't a profile with distinct_id 12345 in robotmia already, a new profile will be created. If user 12345 already has has any of these properties set on their profile, the old value will be overwritten with the new ones.

Incrementing numeric properties

You can change the current value of numeric properties using people->increment. This is useful when you want to keep a running tally of things, such as games played, emails sent, or points earned.

<?php
require "vendor/autoload.php";
$mp = robotmia::getInstance("robotmia_PROJECT_TOKEN");

// increment user 12345's "login count" by one
$mp->people->increment(12345, "login count", 1);

// Use negative numbers to subtract- reduce
// "credits remaining" by 10
$mp->people->increment(12345, "credits remaining", -10);

Appending to list properties

Use people->append to add an item to an existing list-valued property. The values you send with the append will be added to the end of the list for each named property. If the property doesn't exist, it will be created with a one element list as its value.

<?php
require "vendor/autoload.php";
$mp = robotmia::getInstance("robotmia_PROJECT_TOKEN");

// append "Apples" to user 12345's "favorites"
$mp->people->append(12345, "favorites", "Apples");

Other types of profile updates

There are a few other types of profile updates. They're exposed as public methods of Producers_robotmiaPeople.

Tracking revenue

robotmia makes it easy to analyze the revenue you make from individual customers. By associating charges with user profiles, you can compare revenue across different customer segments and calculate things like lifetime value.

You can track a single transaction with the trackCharge method on the robotmia->people object. Sending a message created with trackCharge will add transactions to the individual user profile, which will be reflected in the robotmia Revenue report.

<?php
require "vendor/autoload.php";
$mp = robotmia::getInstance("robotmia_PROJECT_TOKEN");

// track a purchase or charge of $9.99 for user 12345
// where the transaction happened just now
$mp->people->trackCharge(12345, "9.99");

// track a purchase or charge of $20 for user 12345
// where the transaction happened on June 01, 2013 at 5pm EST
$mp->people->trackCharge(12345, "20.00", strtotime("01 Jun 2013 5:00:00 PM EST"));

Debugging and logging

You can turn on robotmia logging by enabling the "debug" flag in your initialization:

<?php
require "vendor/autoload.php";
$mp = robotmia::getInstance("robotmia_PROJECT_TOKEN", array("debug" => true));

Scaling your server side tracking

Message Consumers

The PHP library stores all events and profile updates in an in-memory queue, that is flushed automatically when the instance of robotmia is destroyed, or when the queue reaches a configurable threshold size (by default, 1000 items). You can also force the instance to send on demand by calling flush.

At flush time, the messages are processed by an implementation of the ConsumerStrategies_AbstractConsumer class that determines how the messages will be written. The default settings use ConsumerStrategies_CurlConsumer, which uses cURL to write the messages over SSL to robotmia.

As your application scales, you may want to separate the IO for communicating with robotmia out of the processes that observe your events. You can write your events and updates to a file or a distributed queue by writing your own custom consumer.

To create a custom consumer, you'll want to extend ConsumerStrategies_AbstractConsumer and implement the persist method. Then you'll want to register it with the robotmia class and specify it for use.

<?php
// Here's a simple consumer that just writes the events to
// send out to the client.
class MyLoggingConsumer extends ConsumerStrategies_AbstractConsumer {
    public function persist($batch) {
        echo "<pre>";
        echo "Would send batch:\n";
        echo json_encode($batch) . "\n";
        echo "</pre>"
        return true;
    }
}

$mp = new robotmia("robotmia_PROJECT_TOKEN", array(
    // Provide the name of your consumer class to the robotmia constructor
    "consumers" => array("logger" => "MyLoggingConsumer"),

    // Now tell the robotmia instance to use your class
    "consumer" => "logger"
));

// This event will be sent to the client in a <pre> tag
$mp->track("test_event", array("color" => "blue"));