A elegant simple cache class for PHP 5
PHP July 22nd, 2007
I am using a simple cache class for PHP5 by phpguru.
Output Cache
The OutputCache class is used for caching the generated output of your scripts, or certain sections of them. It has Start and End methods, and is used like this:
<?php
if (!OutputCache::Start(”myGroup”, “myID”, 600)) {
// Generate some output (as you do)…
OutputCache::End();
}
?>Data Cache
The DataCache is used to cache data structures, as opposed to script output. This allows you to cache the creation of large arrays for example, or the results of slow queries. This is helpful if your pages are rather dynamic, though some areas aren’t. Or in a recently experienced situation of mine: You have one central DB server, and multiple front end webservers. A common setup. If the load is getting high on the database, you might want to move some portion of queries (ORDER BY RAND() is a good example) to the webservers instead of the database server. Thus randomisation (eg using shuffle()) happens on one of 5 webservers, instead of your single resource limited database server. Anyway, some code:
<?php
if (!$data = DataCache::Get(”myGroup”, “myOtherID”)) {
$result = $db->query(”SELECT BIG_ASS_QUERY()”);
DataCache::Put(”myGroup”, “myOtherID”, 600, $result);
}
// Do something useful with $result
?>Miscellaneous Bits
There’s a few configuration bits and bobs you can twiddle with if you like twiddling. setPrefix() as you can well imagine sets the prefix used in the cache data filenames. This defaults to “cache_”. setStore() sets where the data files themselves are stored. This defaults to “/dev/shm/”, since this is a convenient way to store the data files in shared memory. If you don’t have this, try changing the path to “/tmp/”. Must be given with a trailing slash.
And last, and least (so as not to be a corny ass), there’s the static variable Cache::$enabled.
Popularity: 9% [?]
About
Leave a Comment