Easily Caching Facebook Graph calls

In this article we'll show you how you can easily add caching to your Facebook calls.
When you retrieve FB objects using the PHP Facebook SDK (https://github.com/facebook/php-sdk) you make an
extensive use of the FB web services. Web services involve HTTP calls.
As soon as you loop through objects like this :

<?$vox_album = $facebook->api("/$album_id/photos");
  foreach($vox_album["data"] as $image){
  	$pic_likes = $facebook->api('/'.$image["id"].'/likes');
  ?>
  <div class="imageDiv">
  	<img src="imgres.jpeg" width=22><br>
  	<a target="_blank" href="https://www.facebook.com/photo.php?fbid=<?=$image["id"]?>&set=a.<?=$album_id?>"
  	><img src="<?= $image["picture"] ?>" width=100 class="photo"
  	></a>
  	<b><?= count($pic_likes["data"])?> Likes</b>
  </div>
<?} ?>

A lot of HTTP connexions are made... not good. We need cache !
Before you start creating your own gas station caching layer, continue reading.
The PHP Facebook SDK uses a file "base_facebook.php" in which you'll find the Graph API calls. 

The most important function is :

protected function makeRequest($url, $params, $ch=null)

This function is actually making the HTTP cal to Facebook and returns the result.
This is where we could add some cache. For this we'll use PHP-APC (http://php.net/manual/fr/book.apc.php).
Replace the line:

$result = curl_exec($ch);

by

if(!$result = apc_fetch($url)){
	$result = curl_exec($ch);
	apc_store($url,$result, 1000);
}

In "base_facebook.php". Every HTTP calls will be cached 1.000 seconds in this example. Check your APC settings for memory, etc. 

Demo : Here (a bit slow the first hit)

 Easy...