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
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Hashing the source into the filename makes a content change automatically miss the cache without any manual versioning.
- 2Writing to a temp file then renaming gives readers an all-or-nothing view, since rename is atomic on the same filesystem.
- 3Clearing every prior variant of a key on write prevents orphaned stale fragments from accumulating.
Related explainers
php
<?php class NameParser {
Parsing a full name into components in PHP
string-parsing
arrays
normalization
Intermediate
8 steps
php
<?php namespace App\Services\Checkout;
Validating coupons with Laravel's Pipeline
pipeline
chain of responsibility
transactions
Intermediate
7 steps
go
package api import ( "crypto/sha256"
ETag conditional requests in Gin
http-caching
etag
conditional-requests
Intermediate
6 steps
php
<?php namespace App\Services;
How a password strength validator works in PHP
validation
regular-expressions
data-driven
Intermediate
8 steps
javascript
import { useState, useEffect, useCallback, useRef } from 'react'; const cache = new Map(); const inflight = new Map();
Building a stale-while-revalidate hook in React
caching
request-deduplication
custom-hooks
Advanced
10 steps
php
<?php namespace App\Services;
Building a cached daily leaderboard in Laravel
caching
aggregation
eager-loading
Intermediate
9 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/a-content-hashed-fragment-cache-in-php-explained-php-7a83/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.