Getting started for PHP developers

From the Directed Edge Developer Base
Jump to: navigation, search

PHP.png

Directed Edge makes integrating with our recommendations engine easy with PHP. We provide bindings that handle all of the communication with our server transparently using normal PHP objects.

Getting started

  • Introduction to Recommendations is a good starting point if you're wondering how recommendations work or what they're useful for.
  • API Concepts explains some of the basics of hour our API works and introduces the concepts of items, tags and links, also explained briefly below.
  • Grab the PHP bindings from GitHub and copy the file named PHP/DirectedEdge.php into your project. You'll also want to make sure that you have Pear and HTTP_Request2 installed to use the bindings.

Data modeling

Items and links

To model the data from your site, you'll need to figure out what your items are. Usually they're things like users, products and articles. We represent a relationship between items by links. So, if you have Bob Dylan's "Blonde on Blonde" that you want to say was bought by "John Doe", you create a link from "John Doe" to "Blonde on Blonde".

Identifiers

Usually we don't need to actually know the names of those items — they just need a unique identifier. Typically that's something like customer1 and product1. Most people just use the ID field from their own database. So if you have a MySQL table named products and Blonde on Blonde is at the row with ID 42 then you'd just use product42 as your identifier for that product.

Tags

Items also have tags, so John Doe would probably have a user tag and Blonde on Blonde would have a product tag. Tags don't weigh into the ranking at all — they're just used so that you can filter the sort of results you'd like to get. So if you want to show related products, you'd run a query looking for things with the tag product.

Querying for recommendations

We offer two primary sorts of recommendations, called related and recommended:

Related is for example if you have one product and you want to find similar products, or a user and want to find similar users. To find products related to Blonde on Blonde you'd send a related query for that item, looking for things tagged product.

Recommended is for doing personalized recommendations, e.g. Products Bob is likely to be interested in... To do a recommended query, you would send a request for the item that corresponds to Bob looking for things that are tagged product.

API Documentation

You can find full documentation for the bindings classes here.

Example

ExampleStore is an example of how you'd connect a store with customers, products and purchases to our recommendations engine, including exporting data and querying the web services.

/*
 * Ok, so the basics of how this thing works:
 *
 * It assumes that you have a local database for your store, and that store
 * has a "customer" table and "products" table.  In each of those tables
 * you have a unique ID that corresponds to each customer and product,
 * respectively.
 *
 * It also assumes there's a third table, named "purchases" that has a list of
 * things purchased by customers.  Basically a mapping from the customer ID to
 * the product ID.  All of this is pretty standard store stuff.
 *
 * So, then what this class does is it handles:
 *
 * - Getting that data from those tables over to Directed Edge
 * - Doing incremental updates (adding customers, products, purchases)
 * - Finding products related to a given product
 * - Finding personalized product recommendations for a customer
 *
 * This is really just the starting point; there are some other exciting things
 * that can be done with the API once you've gotten your feet wet.
 */

define('DB_HOST', 'localhost');
define('DB_USER', 'examplestore');
define('DB_PASS', 'password');
define('DB_NAME', 'examplestore');

define('DIRECTEDEDGE_USER', 'examplestore');
define('DIRECTEDEDGE_PASS', 'password');

define('EXPORT_FILE', 'examplestore.xml');

class ExampleStore
{
    private $database;

    public function __construct()
    {

        mysql_connect(DB_HOST, DB_USER, DB_PASS);

        if(!mysql_select_db(DB_NAME))
        {
            throw new Exception("Could not connect to DB.");
        }

        $this->database = new DirectedEdgeDatabase(DIRECTEDEDGE_USER, DIRECTEDEDGE_PASS);
    }

    /**
     * Export the list of products, purchases and customers to an XML file that
     * we can later push to the Directed Edge webservices.
     */

    public function exportFromMySQL()
    {
        $exporter = new DirectedEdgeExporter(EXPORT_FILE);

        foreach($this->getProducts() as $product)
        {
            $item = new DirectedEdgeItem($exporter->getDatabase(), 'product' . $product);
            $item->addTag('product');
            $exporter->export($item);
        }

        foreach($this->getCustomers() as $customer)
        {
            $item = new DirectedEdgeItem($exporter->getDatabase(), 'customer' . $customer);

            foreach($this->getPurchasesForCustomer($customer) as $product)
            {
                $item->linkTo('product' . $product);
            }

            $exporter->export($item);
        }

        $exporter->finish();
    }

    /**
     * Import the file that we created using exportFromMySQL to the Directed Edge
     * webservices.
     */

    public function importToDirectedEdge()
    {
        $this->database->import(EXPORT_FILE);
    }

    /**
     * Create a customer in the Directed Edge database that corresponds to the
     * customer in the local database with $id.
     */

    public function createCustomer($id)
    {
        $item = new DirectedEdgeItem($this->database, 'customer' . $id);
        $item->addTag('customer');
        $item->save();
    }

    /**
     * Create a product in the Directed Edge database that corresponds to the
     * product in the local database with $id.
     */

    public function createProduct($id)
    {
        $item = new DirectedEdgeItem($this->database, 'product' . $id);
        $item->addTag('product');
        $item->save();
    }

    /**
     * Create a purchase in the Directed Edge database from the product with
     * the local database IDs $customerId and $productId.
     */

    public function addPurchase($customerId, $productId)
    {
        $item = new DirectedEdgeItem($this->database, 'customer' . $customerId);
        $item->linkTo('product' . $productId);
        $item->save();
    }

    /**
     * Returns a list of related product IDs for the product ID that's passed in.
     */

    public function getRelatedProducts($productId)
    {
        $item = new DirectedEdgeItem($this->database, 'product' . $productId);
        $related = array();

        foreach($item->getRelated(array('product')) as $item)
        {
            $related[] = str_replace('product', '', $item);
        }

        return $related;
    }

    /**
     * Returns a list of recommended products for the customer ID that's passed in.
     */

    public function getPersonalizedRecommendations($customerId)
    {
        $item = new DirectedEdgeItem($this->database, 'customer' . $customerId);
        $recommended = array();

        foreach($item->getRecommended(array('product')) as $item)
        {
            $recommended[] = str_replace('product', '', $item);
        }

        return $recommended;
    }

    private function getCustomers()
    {
        $result = mysql_query("select id from customers");
        $customers = array();

        while($row = mysql_fetch_row($result))
        {
            $customers[] = $row[0];
        }

        return $customers;
    }

    private function getProducts()
    {
        $result = mysql_query("select id from products");
        $products = array();

        while($row = mysql_fetch_row($result))
        {
            $products[] = $row[0];
        }

        return $products;
    }

    private function getPurchasesForCustomer($customer)
    {
        $result = mysql_query(sprintf("select product from purchases where customer = '%s'",
                                      mysql_real_escape_string($customer)));
        $purchases = array();

        while($row = mysql_fetch_row($result))
        {
            $purchases[] = $row[0];
        }

        return $purchases;
    }
}

$store = new ExampleStore();
$store->exportFromMySQL();
$store->importToDirectedEdge();

$store->createCustomer(1000);
$store->createProduct(1000);
$store->addPurchase(1000, 1000);

print_r($store->getRelatedProducts(2));
print_r($store->getPersonalizedRecommendations(2));

Further Reading

If you want to dig deeper into how the web services work — the REST API, XML Format and Web Services Examples articles explain what's going on behind the scenes when you use our bindings.