Application Caching with Cache_Lite
When developing a web application using PHP, it is important to follow best practices for optimizing memory usage, database access, and file sizes. All these thing taken into account for, you will likely still find parts of an application to be bulky, or you may find repeated data calls an unnecessary overhead. When you need it, you should use Cache_Lite.
Cache_Lite is a PEAR package that takes a string or buffer input, serializes it, and stores it to a file with a unique id-based hash and a time-to-live (TTL). Cache files are stored and retrieved in your code using this id – so ids must vary for multiple cache files stored. The following tutorial will use Cache_Lite to cache a remote RSS feed.
First we create the instance of Cache_Lite:
require_once('Cache/Lite.php');
$objCache = new Cache_Lite(array("cacheDir"=>"path/to/cacheStorage/", "lifeTime"=>14400));
In the call to the constructor we include the directory we want cache files stored in, and our TTL in seconds. This particular TTL is 4 hours (60 x 60 x 4 = 14400). Next we attempt to read our cache file.
if($rssFeed = $objCache->get("rssFeed")) {
echo $rssFeed;
}
If the file matching the id “rssFeed” exists, we simply output that to the screen. If the file does not exist, we must do our normal RSS parsing – but now we store all the data in a variable, $str, and both 1)Output $str (The first 5 entries of the RSS feed) to the screen, and 2)Save $str as a cache file:
else {
$rssParser = @simplexml_load_file('http://YOURFEEDURL.rss');
$str = $rssParser->channel->title;
for($i=0; $i<5; $i++) {
$item = $rssParser->channel->item[$i];
$itemTitle = htmlentities($item->title, ENT_QUOTES);
$itemDesc = htmlentities($item->description, ENT_QUOTES);
$str .= $itemTitle . ' - ' . $itemDesc . '[...]';
}
echo $str;
$objCache->save($str, "rssFeed");
}
Note: the above code block has had error-checking removed, as well as any output formatting.
If you check your cache directory, you should find a file name with a hash of the id you saved. When you reload the page, the cache file will be read, and you will not have to make a remote connection and parse a feed with each page load!
This tutorial has covered using Cache_Lite to cache an RSS feed, with a TTL of 4 hours – pretty reasonable for an RSS feed update. You can also set a buffer using Cache_Lite_Output (see the end-user docs), which will handle more than just a simple string.
Remember, caching is not a crutch! Use it to squeeze out the unneccesary overhead of your application, and remember that using Cache_Lite turns dynamic data into static data for the TTL.


ShareThis