1<?php
2/**
3 * The following example demonstrates how you might implement caching
4 * for HTTP requests that are being made.  In this case, we make requests
5 * to the GitHub api to retrieve couchbaselabs events and cache the result
6 * of this request for 5 seconds to reduce the load on GitHub.
7 */
8
9/*
10 * Create a new Cluster object to represent the connection to our
11 * cluster and specify any needed options such as SSL.
12 */
13$cb = new \Couchbase\Cluster('couchbase://localhost');
14
15/*
16 * We open the default bucket to store our cached data in.
17 */
18$db = $cb->openBucket('default');
19
20
21/*
22 * Lets define a function which can wrap executing the curl request and
23 * handling the cache in one.
24 */
25function cached_curl_request($path) {
26    global $db;
27
28    /*
29     * Lets define a key to use for storing out cached request into.  We
30     * base this key directly on the path so that we can support caching
31     * many different URIs.  We also add a prefix for good measure.
32     */
33    $cache_key = 'cache_' . $path;
34
35    /*
36     * First we make an attempt to retrieve the data from our cache key,
37     * if the request fails, an exception will be thrown and we will perform
38     * some additional logic rather than returning the value directly.
39     */
40    try {
41        return $db->get($cache_key);
42    } catch (Exception $e) {
43    }
44
45    /*
46     * Since our attempts to retrieve the data we want from our cache failed,
47     * we will have to perform the request ourselves.  The following blurb
48     * simply executes an HTTP request and stores the result (in json decoded
49     * format) into $result.
50     */
51    $curl = curl_init();
52    curl_setopt_array($curl, array(
53        CURLOPT_RETURNTRANSFER => 1,
54        CURLOPT_USERAGENT => 'Couchbase-Example-App',
55        CURLOPT_URL => $path
56    ));
57    $result = json_decode(curl_exec($curl));
58    curl_close($curl);
59
60    /*
61     * Now that we've managed to execute the request, we wil attempt to store
62     * this data onto Couchbase Server for the next request to read rather than
63     * performing another HTTP request.  We perform an insert or update store
64     * store the data into our cache key document, we ignore any failures that
65     * occur since we already have performed the request and are just caching.
66     */
67    try {
68        $db->upsert('cache_' . $path, $result, array('expiry'=>5));
69    } catch (Exception $e) {
70    // Ignore errors, since we are only caching data anyways.
71    }
72
73    /*
74     * Return the result we retrieved earlier
75     */
76    return $result;
77}
78
79/*
80 * Lets set up a URI to test on.
81 */
82$testUri = 'https://api.github.com/users/couchbaselabs/events';
83
84/*
85 * Now we use our caching request function to perform the request and dumb
86 * the results to the page or console.
87 */
88$pageval = cached_curl_request($testUri);
89var_dump($pageval);
90