PHP 7: Maintaining and Upgrading Legacy Apps · Performance on PHP 7
Adding Caching to a Legacy App
Introduce APCu, Redis and HTTP caching without large rewrites.
Quick wins for legacy apps: cache expensive queries and computed fragments in APCu (single server) or Redis (shared), cache full pages for anonymous users at a reverse proxy (Varnish, Nginx fastcgi_cache, or a CDN), and add Cache-Control headers to static assets. Wrap caching in a small helper so keys and TTLs are consistent, and invalidate on writes.
<?php
function remember(string $key, int $ttl, callable $compute)
{
$value = apcu_fetch($key, $hit);
if ($hit) {
return $value;
}
$value = $compute();
apcu_store($key, $value, $ttl);
return $value;
}
$categories = remember('categories:v3', 600, function () use ($pdo) {
return $pdo->query('SELECT id, name FROM categories ORDER BY name')->fetchAll(PDO::FETCH_ASSOC);
});
// After admin edits categories: apcu_delete('categories:v3');
Common pitfalls
- Full-page caching pages that contain user-specific data.
- APCu on multiple servers with inconsistent invalidation.
- No TTLs, so stale data lives forever.
Key points
- APCu per server, Redis shared
- Page caching for anonymous traffic
- Invalidate on writes; always set TTLs
Further reading: PHP manual: APCu
Practice questions
What's the danger of Nginx fastcgi_cache on a site with logins?
Answer
Pages rendered for a logged-in user could be served to others. Bypass the cache when a session cookie is present and only cache anonymous responses.
Why include a version in cache keys (categories:v3)?
Answer
Changing the key format or data shape after a deploy automatically avoids reading stale or incompatible cached data.
Open in the app to mark lessons complete, take notes and track your progress.