PHP文件缓存与静态页面生成 PHP文件缓存与静态页面生成文件缓存是最直接的缓存方式。不用安装Redis或Memcached直接用文件系统做缓存。今天说说文件缓存的实现和页面静态化。文件缓存的核心逻辑是检查缓存文件是否存在且未过期。phpclass FileCache{private string $cacheDir;private int $defaultTtl;public function __construct(string $cacheDir /tmp/cache, int $defaultTtl 3600){$this-cacheDir rtrim($cacheDir, /);$this-defaultTtl $defaultTtl;if (!is_dir($this-cacheDir)) mkdir($this-cacheDir, 0755, true);}public function get(string $key, mixed $default null): mixed{$path $this-getPath($key);if (!file_exists($path)) return $default;$entry unserialize(file_get_contents($path));if ($entry false || time() $entry[expires]) {if (file_exists($path)) unlink($path);return $default;}return $entry[value];}public function set(string $key, mixed $value, ?int $ttl null): bool{$ttl $ttl ?? $this-defaultTtl;$entry [value $value, expires time() $ttl];return file_put_contents($this-getPath($key), serialize($entry), LOCK_EX) ! false;}public function remember(string $key, callable $callback, ?int $ttl null): mixed{$value $this-get($key);if ($value ! null) return $value;$value $callback();$this-set($key, $value, $ttl);return $value;}public function delete(string $key): bool{$path $this-getPath($key);if (file_exists($path)) return unlink($path);return true;}public function flush(): void{array_map(unlink, glob($this-cacheDir . /*.cache));}private function getPath(string $key): string{return $this-cacheDir . / . md5($key) . .cache;}}$cache new FileCache(/tmp/cache, 300);$data $cache-remember(expensive_data, function () {sleep(2);return [result 缓存的数据, time microtime(true)];}, 60);print_r($data);?静态页面生成是PHP性能优化的重要手段。把动态页面生成静态HTML后续请求直接返回静态文件。phpclass StaticPageGenerator{private string $staticDir;private string $templateDir;public function __construct(string $staticDir /var/www/static){$this-staticDir rtrim($staticDir, /);if (!is_dir($this-staticDir)) mkdir($this-staticDir, 0755, true);}public function generate(string $pageName, array $data): string{$html $this-renderTemplate($pageName, $data);$path $this-staticDir . / . $pageName . .html;file_put_contents($path, $html, LOCK_EX);return $path;}public function renderTemplate(string $template, array $data): string{extract($data);ob_start();include $this-templateDir . / . $template . .php;return ob_get_clean();}public function serveStatic(string $pageName): bool{$path $this-staticDir . / . $pageName . .html;if (file_exists($path)) {readfile($path);return true;}return false;}public function cleanExpired(int $maxLifetime 86400): int{$cleaned 0;foreach (glob($this-staticDir . /*.html) as $file) {if (time() - filemtime($file) $maxLifetime) {unlink($file);$cleaned;}}return $cleaned;}}?文件缓存适合中小项目实现简单不需要额外依赖。但高并发场景下文件IO会成为瓶颈这时候应该用Redis或Memcached。页面静态化适合内容变化不频繁的页面比如新闻、文章等。