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 namespace App\Http\Controllers;
Streaming a filtered CSV export in Laravel
streaming
csv-export
query-builder
Intermediate
9 steps
php
<?php namespace App\Http\Middleware;
Idempotent requests with Laravel middleware
idempotency
middleware
caching
Advanced
8 steps
python
from django.contrib.postgres.search import SearchQuery, SearchRank, SearchVector from django.core.cache import cache from django.db.models import F from django.http import JsonResponse
Ranked full-text search in Django
full-text-search
debouncing
caching
Advanced
9 steps
php
<?php namespace App\Services;
Batch image resizing with PHP GD
image-processing
constructor-promotion
match-expression
Intermediate
10 steps
go
func ServeVideo(c *gin.Context) { id := c.Param("id") video, err := videoRepo.FindByID(c.Request.Context(), id) if err != nil {
Streaming video files with Gin
http streaming
range requests
file serving
Intermediate
6 steps
typescript
import { Injectable, OnModuleInit, Logger } from '@nestjs/common'; import { ConfigService } from '@nestjs/config'; import { Cron, CronExpression } from '@nestjs/schedule';
A self-refreshing feature flags provider in NestJS
caching
scheduled-tasks
dependency-injection
Intermediate
8 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.