PDA

View Full Version : An elegant caching solution for the API client


currentstyle
23-08-09, 17:36
With the new quota system in place then it makes sense to cache all pages to minimise on API calls, heres a solution.


Create a folder within your API website called /tmp/cache
Save this code as classes/class.cache.php


<?
class cache
{
var $cache_dir = './tmp/cache/';//This is the directory where the cache files will be stored;
var $cache_time = 86400;//How much time will keep the cache files in seconds. (86400 seconds = 24 hours)

var $caching = false;
var $file = '';

function cache()
{
//Constructor of the class
$this->file = $this->cache_dir . urlencode( $_SERVER['REQUEST_URI'] );
if ( file_exists ( $this->file ) && ( fileatime ( $this->file ) + $this->cache_time ) > time() )
{
//Grab the cache:
$handle = fopen( $this->file , "r");
do {
$data = fread($handle, 1024);
if (strlen($data) == 0) {
break;
}
echo $data;
} while (true);
fclose($handle);
exit();
}
else
{
//create cache :
$this->caching = true;
ob_start();
}
}

function close()
{
//You should have this at the end of each page
if ( $this->caching )
{
//You were caching the contents so display them, and write the cache file
$data = ob_get_clean();
echo $data;
$fp = fopen( $this->file , 'w' );
fwrite ( $fp , $data );
fclose ( $fp );
}
}
}
?>


Then in each page you want to cache add this code above the <html>


<?
require_once('classes/class.cache.php');
$swAPIcache = new cache();
?>


and add this code below the </html>


<?
$swAPIcache->close();
?>


With many thanks to Nick @ http://www.depiction.net/tutorials/php/cachingphp.php

Edit, just realised I posted this in the wrong forum.

parkerproject
11-12-11, 14:57
Thanks for sharing.