Implementing a Data Cache Class in PHP for Efficient Web Applications
This article explains how to improve PHP application performance by implementing a data caching class, illustrates a weather‑API example, shows how to set cache duration, avoid duplicate data storage, and discusses production considerations such as concurrency, large data, security, and expiration handling.
Data caching can effectively improve PHP program performance by avoiding repeated calculations or data retrieval.
For example, a web application uses a weather API that provides identical data for all users and updates only once per hour, but each request takes about 15 seconds.
By caching the first user's response, subsequent users receive the data instantly, greatly enhancing user experience and application availability.
An optional improvement is to schedule a task that runs hourly to refresh the cache, ensuring even the first user gets a quick answer, though this increases API usage and may fail if the task encounters errors.
The following code demonstrates how to use a simple cache management class in PHP:
$data_clima = false;
// Create cache object
$cache = new DataCache();
// Check if cache file is valid
if ($cache->read('api-clima')) {
// Restore cached data
$data_clima = $cache->getData();
} else {
// Use external API
$data_clima = get_api_clima();
// Generate cache file
$cache->save($data_clima);
}To set a cache duration of one hour (3600 seconds) and save the data:
$data_clima = get_api_clima();
// Set cache duration
$cache->duration(3600);
// Generate cache file
$cache->save($data_clima);To avoid keeping two copies of the same data in memory, the cache can export the data directly into a variable:
if ($cache->read('api-clima')) {
// Restore cached data
$cache->exportInto($data_clima);
}The complete implementation of the DataCache class is shown below:
class DataCache {
private string $filename = '';
private mixed $data = false;
private int $maxtime = 0;
/**
* Read cache file.
*
* @param string $name Name associated with the data to be cached
* @return bool TRUE if the data could be recovered.
*/
public function read(string $name) {
$this->maxtime = 0;
$this->data = false;
$this->filename = '';
$result = false;
if (trim($name) !== '') {
$this->filename = sys_get_temp_dir() . DIRECTORY_SEPARATOR . 'cache-' . md5(strtolower($name));
if (file_exists($this->filename)) {
$this->data = unserialize(file_get_contents($this->filename));
$result = (is_array($this->data) && array_key_exists('data', $this->data) && array_key_exists('maxtime', $this->data));
if ($result && $this->data['maxtime'] > 0) {
$result = (time() <= $this->data['maxtime']);
}
if (!$result) {
$this->data = false;
} else {
$this->maxtime = $this->data['maxtime'];
$this->data = $this->data['data'];
}
}
}
return $result;
}
/**
* Returns the recovered data from the cache.
*
* @return mixed Data recovered or FALSE if not available.
*/
public function getData() {
return $this->data;
}
/**
* Associate the recovered data from the cache to a variable and then remove from memory.
*
* @param mixed $data Variable in which the data returns.
*/
public function exportInto(mixed &$data) {
$data = $this->data;
$this->data = false;
}
/**
* Generates a new cache file with the data indicated.
*
* @param mixed $data Data to be saved in the cache file.
* @return bool TRUE if the data could be saved to the file.
*/
public function save(mixed $data) {
$result = false;
if ($this->filename != '') {
$bytes = file_put_contents(
$this->filename,
serialize(array('data' => $data, 'maxtime' => $this->maxtime))
);
if ($bytes > 0) {
$this->data = $data;
$result = true;
}
}
return $result;
}
/**
* Time in seconds for which the data in the cache are valid.
* Must be greater than or equal to zero. Value of zero removes limit.
*
* @param int $seconds
*/
public function duration(int $seconds) {
if ($seconds >= 0) {
$this->maxtime = time() + $seconds;
}
}
}When deploying this cache class in production, consider concurrency control (e.g., file locks), handling large data volumes, encrypting sensitive cached data, and regularly cleaning up expired entries via scheduled tasks.
php中文网 Courses
php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.