Lesson 2 of 6
Application Caching - APCu & Redis
Application-level caching stores the results of expensive operations - database queries, rendered HTML, computed aggregates - and returns them instantly on subsequent requests. APCu is per-process in-memory (fast, no network, lost on restart). Redis is a shared, persistent, networked cache (survives restarts, shared across multiple servers).
APCu, Redis & Cache Abstraction Layer
<?php
declare(strict_types=1);
// ── Cache interface - swap backends without changing callers ──
interface CacheInterface {
public function get(string $key, mixed $default = null): mixed;
public function set(string $key, mixed $value, int $ttl = 3600): bool;
public function delete(string $key): bool;
public function clear(): bool;
public function has(string $key): bool;
public function remember(string $key, int $ttl, callable $callback): mixed;
}
// ── APCu - in-process shared memory cache ─────────────────────
// Fastest possible - no network, no serialisation overhead
// Scope: current PHP-FPM worker pool (not shared between servers)
class ApcuCache implements CacheInterface {
public function get(string $key, mixed $default = null): mixed {
$value = apcu_fetch($key, $success);
return $success ? $value : $default;
}
public function set(string $key, mixed $value, int $ttl = 3600): bool {
return apcu_store($key, $value, $ttl);
}
public function delete(string $key): bool { return apcu_delete($key) !== false; }
public function clear(): bool { return apcu_clear_cache(); }
public function has(string $key): bool { return apcu_exists($key); }
public function remember(string $key, int $ttl, callable $callback): mixed {
if ($this->has($key)) return $this->get($key);
$value = $callback();
$this->set($key, $value, $ttl);
return $value;
}
}
// ── Redis Cache - networked, persistent, multi-server ─────────
// composer require predis/predis OR use ext-redis (C extension)
class RedisCache implements CacheInterface {
private Redis $redis;
public function __construct(string $host = "127.0.0.1", int $port = 6379, int $db = 0) {
$this->redis = new Redis();
$this->redis->connect($host, $port, timeout: 1.0);
$this->redis->select($db);
}
public function get(string $key, mixed $default = null): mixed {
$raw = $this->redis->get($key);
if ($raw === false) return $default;
return unserialize($raw);
}
public function set(string $key, mixed $value, int $ttl = 3600): bool {
return $this->redis->setex($key, $ttl, serialize($value));
}
public function delete(string $key): bool { return (bool) $this->redis->del($key); }
public function clear(): bool { return $this->redis->flushDb(); }
public function has(string $key): bool { return (bool) $this->redis->exists($key); }
public function remember(string $key, int $ttl, callable $callback): mixed {
if ($this->has($key)) return $this->get($key);
$value = $callback();
$this->set($key, $value, $ttl);
return $value;
}
// Redis-specific - atomic increment (view counter, rate limit)
public function increment(string $key, int $by = 1): int { return $this->redis->incrBy($key, $by); }
public function expire(string $key, int $seconds): bool { return $this->redis->expire($key, $seconds); }
}
// ── Cache invalidation patterns ───────────────────────────────
class PostService {
public function __construct(
private readonly PostRepositoryInterface $posts,
private readonly CacheInterface $cache,
) {}
private function postCacheKey(int $id): string { return "post:$id"; }
private function feedCacheKey(int $page): string { return "feed:page:$page"; }
public function getPost(int $id): Post {
return $this->cache->remember(
$this->postCacheKey($id),
ttl: 3600,
callback: fn() => $this->posts->findById($id) ?? throw new NotFoundException("Post $id not found.")
);
}
public function publishPost(int $id): Post {
$published = $this->posts->save(/* publish logic */);
// Invalidate related cache entries
$this->cache->delete($this->postCacheKey($id)); // stale individual post
foreach (range(1, 10) as $page) {
$this->cache->delete($this->feedCacheKey($page)); // stale feed pages
}
return $published;
}
// Stampede protection - only one process rebuilds the cache
public function getPostWithLock(int $id): Post {
$key = $this->postCacheKey($id);
$lock = "lock:$key";
$cached = $this->cache->get($key);
if ($cached !== null) return $cached;
// Acquire lock - first request wins
if ($this->cache instanceof RedisCache) {
if (!$this->cache->redis->set($lock, 1, ["nx" => true, "ex" => 10])) {
usleep(50_000); // wait 50ms, try again
return $this->cache->get($key) ?? $this->posts->findById($id);
}
}
$value = $this->posts->findById($id) ?? throw new NotFoundException();
$this->cache->set($key, $value, 3600);
return $value;
}
}Quick Quiz
Tip
Tip
Practice Application Caching APCu Redis in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.
Visual architecture and concepts for Application Caching - APCu & Redis
Practice Task
Note
Practice Task - (1) Write a working example of Application Caching APCu Redis from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.
Common Mistake
Warning
A common mistake with Application Caching APCu Redis is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready php code.
Finished this lesson?