Database design: keys, relationships and normalization
Design tables that avoid duplicated data: primary keys, foreign keys, one-to-many and many-to-many relationships.
Save slow query results to disk for a few minutes and serve them instantly.
Cache data that is slow to build and does not change every second: a homepage list, a statistics query, a remote API response.
<?php
function cache_get(string $key, int $ttl, callable $build)
{
$file = __DIR__ . '/cache/' . md5($key) . '.json';
if (is_file($file) && time() - filemtime($file) < $ttl) {
$data = json_decode((string)file_get_contents($file), true);
if ($data !== null) {
return $data;
}
}
$data = $build();
$tmp = $file . '.' . bin2hex(random_bytes(4));
file_put_contents($tmp, json_encode($data));
rename($tmp, $file); // atomic: readers never see half a file
return $data;
}
$top = cache_get('top-articles', 300, function () use ($pdo) {
return $pdo->query('SELECT id, title FROM articles ORDER BY views DESC LIMIT 10')->fetchAll();
});rename() it, so a visitor never reads a half-written file.cache folder outside public access, or block it in .htaccess.Use the slow query log or timing code to prove a query is the problem before adding a cache. A missing index is often a better fix.
Design tables that avoid duplicated data: primary keys, foreign keys, one-to-many and many-to-many relationships.
A folder layout and a few habits that keep a growing PHP site tidy, secure and easy to maintain.