Store your Twitter API results with Memcache

Recently I needed a dynamic cache function for some PHP based, custom website. Most pages are a kind of mash-up with different results and one of them was dynamic Twitter feed that shows the latest tweets for some static “search” value.

Using the PHP library Twitter OAuth by Abraham is it very easy to create a Twitter search or any other Twitter API request. The only preparation you need to do is, create an app in the Twitter developer section.

$toa = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET, ACCESS_TOKEN, ACCESS_TOKEN_SECRET);
$query = array("q" => 'PHP tutorials', "count" => 5, "result_type" => "recent", "include_entities" => "true");
$tweets = $toa->get('search/tweets', $query);

Thats’s all PHP code you need to get an object with the Twitter statuses related to the search I have provided.

Caching the results using Memcache

Since the “search” query is the same for each mash-up page, it makes no sense to request new tweets for every page view. That’s were a cache function becomes useful.

Install Memcache (ServerPilot only!)

I’m using ServerPilot on the top of my VPS I got from Vultr.com. With ServerPilot it’s very easy to install Memcached and the Memcache PHP library. The following command will install the Memcached server.

sudo apt-get install memcached

The following commands are only necessary if you didn’t installed/compiled a PECL library before. You can ran them anyway because Ubuntu will not install them twice.

apt-get install gcc make autoconf libc-dev
apt-get install zlib1g-dev

The next commands will add the PHP library Memcache for the PHP 5.5 version on your ServerPilot based server. Change the version if you need to 5.4 or 5.6.

pecl5.5-sp install memcache
bash -c "echo extension=memcache.so > /etc/php5.5-sp/conf.d/memcache.ini"

The last thing your need to do is, restart the PHP-FPM.

service php5.5-fpm-sp restart

Cache your Twitter results with Memcache

I used the following code to check if there is a valid cached version for my Twitter result and if not, get a new result and cache it using Memcache.

$search = 'PHP tutorials';
$obj_str = 'tweets_'.str_replace(' ', '_', $search);
$memcache_obj = new Memcache;
$memcache_obj->connect("127.0.0.1", 11211);

if (!$tweets = $memcache_obj->get($obj_str)) {
    $toa = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET, ACCESS_TOKEN, ACCESS_TOKEN_SECRET);
    $query = array("q" => $search, "count" => 5, "result_type" => "recent", "include_entities" => "true");
    $tweets = $toa->get('search/tweets', $query);
    if (!empty($tweets->statuses)) {
        $memcache_obj->set($obj_str, $tweets, 0, 86400);
    }
}

Thats all, use a foreach loop to show the tweets from the $tweets->statuses object.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.