PHP Cache Tools

CacheTools makes it easy to cache the results of a function for later use. Perfect for consuming external XML feeds without needing to fetch them every time a visitor loads your page.

Examples

Once installed and instantiated, it’s easy to use:

function loadXML ($xmlFileURL) {
	return file_get_contents ($xmlFileURL);
}
$xmlDoc = $CacheTools->cachedOrCallback(
	'loadXML',
	$args=array('http://example.com/thefile.xml'),
	300, // cache for 300 seconds (5 minutes)
);

This example will fetch the XML file from the remote URL on first use, then return the file contents from the cache for subsequent calls within the next 5 minutes.

Note: This will only work if the return value of the callback function is serializable—and not all objects are! But there are often workarounds available. For example, here’s a way to get a serializable DOMDocument object.

Installation

  1. Download the release package
  2. Unzip the package (discard the folder with version number)
  3. Add the folder CacheTools to your projects library directory
  4. Ensure the cache directory is writable by the PHP process (by default, this directory sits inside the CacheTools directory)

Use

Once CacheTools is installed you can use it by:

  1. Including the class:
    require_once('CacheTools/class.CacheTools.php');
  2. Instantiating a new CacheTools object
    $CacheTools = new CacheTools();

    Optionally, you can pass a configuration array during instantiation:

    $config = array(
    	'cacheDir'         => '/path/to/cache/directory/', // default is CacheTools/cache/
    	'cleanupEvery'     => 6, // hours (periodically cleans up old cache files)
    	'cleanupOlderThan' => 24, // hours (cleans up cache files older than this value)
    );
    
    $CacheTools= new CacheTools($config);

You can now call the $CacheTools->cachedOrCallback() method (as per examples) to cache the results of a function.

Download

CacheTools is licensed under the The GNU General Public License (GPL), by downloading and/or using it you are agreeing to abide by the terms of that license.

Package

Download the complete CacheTools 0.1 package (.zip)

Changelog

  • Version 0.1: Initial release

Leave a reply