php 63 lines · 10 steps

A content-hashed fragment cache in PHP

A file-backed cache that keys fragments by content hash and writes them atomically so readers never see partial data.

Explained by highlit
1<?php
2 
3namespace App\Cache;
4 
5use RuntimeException;
6 
7final class FragmentCache
8{
9 private string $baseDir;
10 
11 public function __construct(string $baseDir)
12 {
13 $this->baseDir = rtrim($baseDir, '/');
14 if (!is_dir($this->baseDir) && !mkdir($this->baseDir, 0775, true) && !is_dir($this->baseDir)) {
15 throw new RuntimeException("Unable to create cache dir: {$this->baseDir}");
16 }
17 }
18 
19 public function remember(string $key, string $source, callable $render): string
20 {
21 $hash = hash('xxh128', $source);
22 $path = $this->pathFor($key, $hash);
23 
24 if (is_file($path)) {
25 return file_get_contents($path);
26 }
27 
28 $this->invalidate($key);
29 $html = $render();
30 $this->atomicWrite($path, $html);
31 
32 return $html;
33 }
34 
35 public function invalidate(string $key): void
36 {
37 foreach (glob($this->baseDir . '/' . $this->slug($key) . '.*.frag') ?: [] as $stale) {
38 @unlink($stale);
39 }
40 }
41 
42 private function pathFor(string $key, string $hash): string
43 {
44 return sprintf('%s/%s.%s.frag', $this->baseDir, $this->slug($key), $hash);
45 }
46 
47 private function atomicWrite(string $path, string $contents): void
48 {
49 $tmp = $path . '.' . bin2hex(random_bytes(6)) . '.tmp';
50 if (file_put_contents($tmp, $contents, LOCK_EX) === false) {
51 throw new RuntimeException("Failed writing cache: {$path}");
52 }
53 if (!rename($tmp, $path)) {
54 @unlink($tmp);
55 throw new RuntimeException("Failed committing cache: {$path}");
56 }
57 }
58 
59 private function slug(string $key): string
60 {
61 return preg_replace('/[^A-Za-z0-9_-]+/', '_', $key);
62 }
63}
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1Hashing the source into the filename makes a content change automatically miss the cache without any manual versioning.
  2. 2Writing to a temp file then renaming gives readers an all-or-nothing view, since rename is atomic on the same filesystem.
  3. 3Clearing every prior variant of a key on write prevents orphaned stale fragments from accumulating.

Related explainers

Share this explainer

Here's the card — post it anywhere.

A content-hashed fragment cache in PHP — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code