osC_Cache - Caching Class | Last Update: 7th April, 2005 Article ID: 8 |
- Introduction
- Examples
- Class API
Introduction
The caching class is used to store data in a file that is read until the set expiration time has been met.
This improves performance by executing heavy pieces of logic only once, storing the result in a file and is read until the expiration time is met, bypassing the need to execute the heavy piece of logic on each request.
The caching class is able to store data that PHP code has produced, and is able to store results of PHP variables and database queries.
Examples
Caching data produced by PHP for 60 minutes:
<?php
$osC_Cache = new osC_Cache;
if ($osC_Cache->read('uniqueKeyName', 60) === false) {
$osC_Cache->startBuffer();
------ PHP/HTML LOGIC HERE ------
$osC_Cache->stopBuffer();
}
echo $osC_Cache->getCache();
?>
Caching a PHP variable for 30 minutes:
<?php
$osC_Cache = new osC_Cache;
if ($osC_Cache->read('uniqueKeyName', 30) {
$variable = $osC_Cache->getCache();
} else {
$variable = array('some', 'data');
$osC_Cache->writeBuffer($variable);
}
?>
Examples of caching the results of an SQL query can be found on the osC_Database documentation page.
Be sure not to cache data produced by PHP that may contain the session ID (eg, http links inside a HTML block), as this session ID would then be used at a global scale and will pose a privacy and security issue.
Class API
- write($key, &$data)
- read($key, $expire = 0)
- &getCache()
- startBuffer()
- stopBuffer()
- writeBuffer(&$data)
write($key, &$data)
Stores the contents of the $data variable in a file with the name of the $key variable.
Cached files are stored in the DIR_FS_WORK directory, and automatically have the file extension of '.cache'.
read($key, $expire = 0)
Reads the contents of the cached file with the filename of the $key variable, if the expiration time has not yet beed reached.
The expiration time is caculcated by differencing the current time with the creation time of the cached file.
If the $expire value is 0, the cached file is always read until it no longer exists.
&getCache()
Returns the cached value set by the read() method.
startBuffer()
Starts the buffer to read data into.
stopBuffer()
Stops the buffer and writes the contents of the buffer into the cache file.
writeBuffer(&$data)
Writes the contents of the $data variable to the cache file.