Friday, February 4, 2011

Storing variable or other data using pear cache

You can do this by using the base cache class:
require_once(“Cache.php”);

$cache = new Cache(“file”, array(“cache_dir” => “cache/”) );
$id = $cache->generateID(“this is a unique key”);

if ($data = $cache->get($id)) {

print “Cache hit.
Data: $data”;

} else {

$data = “The quality of mercy is not strained…”;
$cache->save($id, $data, $expires = 60);
print “Cache miss.
”;

}

To save the data we use save(). If your unique key is already a legal file name, you can bypass the generateID() step. Objects and arrays can be saved because save() will serialize the data for you. The last parameter controls when the data expires; this can be the seconds to cache the data, or a Unix integer timestamp giving the date and time to expire the data, or zero to use the default of 24 hours. To retrieve the cached data we use get().

You can delete a cached data item using $cache->delete($id) and remove all cached items using $cache->flush().

New: A faster Caching class is Cache-Lite. Highly recommended.

1 comment: