How to implement caching system in php for json api

I have several custom social buttons on my website for which I get the number / subscribers number using json from the API. I tried to implement a caching system to reduce load time and eliminate the risk of being “red” for excessive use of the API. However, I was not successful in this area, mainly because I do not quite understand the steps to integrate. I hope someone can help me integrate the caching system.

Here are the php codes for Twitter, Google Plus and Instagram:

  • Twitter
    ob_start ();
    $ twittershare = 'http://cdn.api.twitter.com/1/urls/count.json?url='.$product["href "].' ';

    $ ch = curl_init ();
    curl_setopt ($ ch, CURLOPT_URL, $ twittershare);
    curl_setopt ($ ch, CURLOPT_HEADER, 0);
    $ jsonstring = curl_exec ($ ch);
    curl_close ($ ch);
    $ bufferstr = ob_get_contents ();
    ob_end_clean ();
    $ json = json_decode ($ bufferstr);

    echo $ json-> count;

  • Google plus
    $ url = ''. $ product ["href"]. '';

    $ ch = curl_init ();
    curl_setopt ($ ch, CURLOPT_URL, "https://clients6.google.com/rpc?key=xxxxxxxxxx");
    curl_setopt ($ ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, '[{"method":"pos.plusones.get","id":"p","params":{"nolog":true,"id":"' . $url . '","source":"widget","userId":"@viewer","groupId":"@self"},"jsonrpc":"2.0","key":"p","apiVersion":"v1"}]');
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-type: application/json'));
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    $curl_results = curl_exec($ch);
    curl_close($ch);
    $json = json_decode($curl_results, true);
    $count = intval($json[0]['result']['metadata']['globalCounts']['count']);
    $data = array();
    $data['plus_count'] = (string) $count;
    $data['url'] = $url;
    echo $data['plus_count'];

  • Instagram ( )
    ob_start();
    $insta = 'https://api.instagram.com/v1/users/00000000?access_token={token}';

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $insta);
    curl_setopt($ch, CURLOPT_HEADER, 0);
    $jsonstring = curl_exec($ch);
    curl_close($ch);
    $bufferstr = ob_get_contents();
    ob_end_clean();
    $json = json_decode($bufferstr);

    echo $json->data->counts->followed_by;

, , , , .

+4
1

, , Memcached , ( PDO twitter) Memcached .;) AJAX, , , .

:

CREATE TABLE IF NOT EXISTS `Followers` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `url` varchar(100) NOT NULL,
  `data` longtext NOT NULL,
  `followers` int(5) NOT NULL,
  `last_update` TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=utf8;

, - :

interface SocialFollowers
{
    public function getFollowers();
}

API- twitter , URL . ( ). , , API , , .

class TwitterFollowers implements SocialFollowers
{
    private $data = null;
    private $url = "";
    private $db = null;
    private $followers = null;

    protected $shareURL = "https://cdn.api.twitter.com/1/urls/count.json?url=";

    public function __construct($db, $url) {
        // initialize the database connection here
        // or use an existing handle
        $this->db = $db;

        // store the url
        $this->url = $url;

        // fetch the record from the database
        $stmt = $this->db->prepare('SELECT * FROM `Followers` WHERE url = :url ORDER BY last_update DESC LIMIT 1');
        $stmt->bindParam(":url", $url);
        $stmt->execute();

        $this->data = $stmt->fetch(PDO::FETCH_ASSOC);
        if (!empty($this->data))
            $this->followers = $this->data["followers"];
    }

    public function getFollowers()
    {
        // create a timestamp that 30 minutes ago
        // if it newer than the value from the database -> call the api
        $old = new DateTime();
        $old->sub(new DateInterval("PT30M"));

        if (is_null($this->followers) || (new DateTime($this->data["last_update"]) < $old) ) {
            return $this->retrieveFromAPI();
        }

        return $this->followers;
    }

    private function retrieveFromAPI()
    {
        // mostly untouched
        ob_start();
        $twittershare = $this->shareURL . $this->url;

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $twittershare);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        $jsonstring = curl_exec($ch);
        curl_close($ch);
        $bufferstr = ob_get_contents();
        ob_end_clean();
        $json = json_decode($bufferstr);

        $this->followers = $json->count;

        // store the retrieved values in the database
        $stmt = $this->db->prepare('INSERT INTO Followers (url, data, followers)'
            .'VALUES (:url, :data, :followers)');
        $stmt->execute(array(
            ":url" => $this->url,
            ":data" => $bufferstr,
            ":followers" => $this->followers
        ));

        return $this->followers;
    }
}

Facebook, Google+, - .

, , . try/catch PDO (: - , URL-, blob ..).

, .

[edit] ( ) . github. , , - ajax ( jQuery),

$.ajax({
    url: "http://example.com/twitter.php",
    type: "get",
    data: {url: "http://stackoverflow.com"}
    success: function(data, textStatus, jqXHR) {
        // Update the corresponding counter like
        // $("#twitterfollowers").text(data);
        console.log(data);
    }
});
+2

All Articles