<?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());
Create a free account and build your private vault. Share publicly whenever you want.