Implementing a PHP DataCache Class for Efficient Web Application Performance

This article explains how to improve PHP application performance by creating a reusable DataCache class that stores API results, demonstrates usage with a weather‑API example, shows code for reading, saving, and expiring cached data, and discusses production considerations such as concurrency, large data handling, security, and cleanup.

php Courses
php Courses
php Courses
Implementing a PHP DataCache Class for Efficient Web Application Performance

Data caching can significantly boost the performance of PHP programs by avoiding repeated calculations or data retrievals, and the best approach is to create a dedicated cache system to manage the stored data.

Consider a web application that fetches current weather information from an external API; each request takes about 15 seconds, but the data changes only once per hour and is identical for all users. Without caching, every user must wait the full 15 seconds, leading to a poor experience.

By caching the first request’s result, subsequent users receive the data instantly, dramatically improving responsiveness. A simple usage example is shown below:

$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 ensure the cache updates hourly, the duration can be set before saving:

$data_clima = get_api_clima();
// Set cache lifetime to one hour (3600 seconds)
$cache->duration(3600);
// Save cache file
$cache->save($data_clima);

This marks the cached data as valid for the next hour. An additional optimization avoids keeping two copies of the same data in memory by using an exportInto() method that copies the cached data directly into a variable without storing it in the cache object:

if ($cache->read('api-clima')) {
    // Restore cached data directly into variable
    $cache->exportInto($data_clima);
}

The complete implementation of the DataCache class is provided below, including methods for reading, retrieving, exporting, saving, and setting cache duration:

class DataCache {
    private string $filename = '';
    private mixed $data = false;
    private int $maxtime = 0;

    /** Read cache file. */
    public function read(string $name): bool {
        $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. */
    public function getData() {
        return $this->data;
    }

    /** Export the recovered data into a variable and remove it from memory. */
    public function exportInto(mixed &$data) {
        $data = $this->data;
        $this->data = false;
    }

    /** Save data to a new cache file. */
    public function save(mixed $data): bool {
        $result = false;
        if ($this->filename != '') {
            $bytes = file_put_contents(
                $this->filename,
                serialize(['data' => $data, 'maxtime' => $this->maxtime])
            );
            if ($bytes > 0) {
                $this->data = $data;
                $result = true;
            }
        }
        return $result;
    }

    /** Set cache validity time in seconds (0 removes limit). */
    public function duration(int $seconds) {
        if ($seconds >= 0) {
            $this->maxtime = time() + $seconds;
        }
    }
}

When deploying this simple cache manager in production, consider additional factors: concurrent access (use file locks or transactions), handling very large data sets (benchmark read/write performance), protecting sensitive data (encrypt cache files), and regularly cleaning expired entries (via scheduled tasks).

By following these guidelines, developers can effectively reduce latency, lower API usage, and improve overall application scalability.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

backendPerformancecachingweb-developmentDataCache
php Courses
Written by

php Courses

php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.