PHP Data Caching: Structures, Index Design Principles, and Code Examples
This article explains PHP data caching techniques—including memory, file, and database caches—provides practical code samples, and outlines key index design principles such as uniqueness, expiration, hotspot optimization, efficient updates, and hierarchical caching to improve performance.
Data Cache Structures
Memory Cache
Memory cache stores data in RAM for fast access, commonly using Memcache or Redis. Example using PHP Memcache extension:
<code><?php
$memcache = new Memcache;
$memcache->connect('127.0.0.1', 11211) or die ("Could not connect");
$key = "user_data_1";
$data = $memcache->get($key);
if($data === false){
// fetch from DB
$data = getUserDataFromDB(1);
// store in cache for 1 hour
$memcache->set($key, $data, 0, 3600);
}
// use $data
...?>
</code>File Cache
File cache saves data to a file, often in JSON format. Example using PHP file functions:
<code><?php
$cacheFile = "user_data_1.json";
if (file_exists($cacheFile) && time() - filemtime($cacheFile) < 3600) {
// read from cache file
$data = json_decode(file_get_contents($cacheFile), true);
} else {
// fetch from DB
$data = getUserDataFromDB(1);
// write to cache file
file_put_contents($cacheFile, json_encode($data));
}
// use $data
...?>
</code>Database Cache
Database cache stores data in a DB, e.g., MySQL Memory engine or Redis. Example using PDO with a cache table:
<code><?php
$pdo = new PDO('mysql:host=localhost;dbname=test;charset=utf8', 'username', 'password');
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$cacheTable = "user_data_cache";
$stmt = $pdo->prepare("SELECT * FROM $cacheTable WHERE id = ?");
$stmt->execute([1]);
$row = $stmt->fetch(PDO::FETCH_ASSOC);
if ($row) {
$data = json_decode($row['data'], true);
} else {
$data = getUserDataFromDB(1);
$stmt = $pdo->prepare("INSERT INTO $cacheTable(id, data) VALUES(?, ?)");
$stmt->execute([1, json_encode($data)]);
}
// use $data
...?>
</code>Index Design Principles for Data Cache
Good index design improves cache read efficiency. Principles include unique keys, appropriate expiration, hotspot data optimization, efficient cache updates, and hierarchical caching.
Unique Index
Ensure cache keys are unique, e.g., using user ID as key in Memcache.
Consider Cache Expiration
Set suitable expiration times to avoid stale data, such as checking file modification time for file cache.
Hotspot Data Optimization
Pre‑load frequently accessed data into cache, e.g., storing hot rows directly in a cache table.
Efficient Cache Updates
Keep cache and database consistent, using triggers or stored procedures for automatic updates.
Cache Hierarchy
Use nested cache keys for multi‑level data, like combining user ID and data type.
Conclusion
By selecting appropriate cache structures and applying index design principles, PHP applications can achieve better performance and responsiveness.
php中文网 Courses
php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.