写给愿意动手的 PHP 开发者
PHP学习网 PHP学习网
公告PHP学习网为公益性网站,致力于为广大PHP爱好者服务
首页/ PHP 源码/ 文件缓存:带过期与原子写入
系统与运维 通用 PHP 7.4+

文件缓存:带过期与原子写入

把计算结果缓存成文件,先写临时文件再 rename,避免读到写了一半的内容;支持过期与删除。

完整代码

PHP
<?php
class FileCache
{
    private string $dir;

    public function __construct(string $dir)
    {
        $this->dir = rtrim($dir, '/');
        if (!is_dir($this->dir)) {
            @mkdir($this->dir, 0755, true);
        }
    }

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

    public function get(string $key, $default = null)
    {
        $file = $this->path($key);
        if (!is_file($file)) {
            return $default;
        }
        $raw = @file_get_contents($file);
        if ($raw === false) {
            return $default;
        }
        $pos = strpos($raw, "\n");
        if ($pos === false) {
            return $default;
        }
        if ((int)substr($raw, 0, $pos) < time()) {
            @unlink($file);
            return $default;
        }
        $val = @unserialize(substr($raw, $pos + 1), ['allowed_classes' => false]);
        return $val === false ? $default : $val;
    }

    public function set(string $key, $value, int $ttl = 300): bool
    {
        $file = $this->path($key);
        $tmp = $file . '.' . getmypid() . '.tmp';
        $data = (time() + $ttl) . "\n" . serialize($value);
        if (@file_put_contents($tmp, $data, LOCK_EX) === false) {
            return false;
        }
        return @rename($tmp, $file);
    }

    public function forget(string $key): void
    {
        @unlink($this->path($key));
    }
}

怎么用

  1. $cache = new FileCache(__DIR__ . '/../cache');
  2. $data = $cache->get('home:list'); if ($data === null) { $data = 查库(); $cache->set('home:list', $data, 300); }
  3. 数据更新时调用 forget 对应的键。

注意

  • rename 在同一分区上是原子的,所以不会读到半个文件;跨分区会退化成复制。
  • unserialize 传 allowed_classes=false,防止缓存文件被篡改后反序列化出对象。
  • 缓存目录放到 Web 根目录外,避免 .cache 文件被直接下载。

相关源码