PHP

Simple File-Backed Cache

admin by @admin ADMIN
1h ago
May 31, 2026
Public
0 0 up · 0 down Sign in to vote
A tiny key-value cache with TTL, persisted as a serialized PHP file per key. Good enough for memoizing expensive computations on a single machine; replace with Redis when scaling out.
PHP
Raw
<?php
final class FileCache {
    public function __construct(private string $dir) {
        if (!is_dir($dir)) mkdir($dir, 0700, true);
    }

    private function path(string $key): string {
        return $this->dir . '/' . sha1($key) . '.cache';
    }

    public function get(string $key): mixed {
        $file = $this->path($key);
        if (!is_file($file)) return null;
        $entry = @unserialize(file_get_contents($file));
        if (!$entry || ($entry['exp'] !== 0 && $entry['exp'] < time())) {
            @unlink($file);
            return null;
        }
        return $entry['val'];
    }

    public function set(string $key, mixed $value, int $ttlSec = 0): void {
        $exp = $ttlSec > 0 ? time() + $ttlSec : 0;
        file_put_contents($this->path($key), serialize(['exp' => $exp, 'val' => $value]), LOCK_EX);
    }

    public function remember(string $key, int $ttl, callable $producer): mixed {
        $v = $this->get($key);
        if ($v !== null) return $v;
        $v = $producer();
        $this->set($key, $v, $ttl);
        return $v;
    }
}

$cache = new FileCache('/tmp/myapp-cache');
$rates = $cache->remember('exchange-rates', 3600, fn() => fetchRatesFromApi());
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.