我有一个项目是几个体育赛事系列的结果数据库。 正如您想象的那样,大多数内容或多或少保持不变。 我想缓存一些内容以保存数据库查询。
该项目是使用 PHP 构建的,并且使用的是自定义 MVC。 您将在哪里添加缓存逻辑?
最佳答案
使用内存缓存。像这样,您缓存查询结果,并尝试在 DB 之前从缓存中检索。
编辑:添加了 json_encoding 数据...json_encode 比 PHP 对数组的默认序列化稍快,并且可以被访问数据的其他应用程序使用
Memcached 默认使用 FastLZ 压缩。
// The ID of the item you're looking for (from $_GET or whatever)
$id = 1;
// Create a memcached instance
$m = new Memcached();
$m->addServer('localhost', 11211);
// Try retrieving the event from memcached
$data = $m->get('event_' . $id);
if ($data) {
// If you found data in memcached, decode it for use in code
$data = json_decode($data);
} else {
// If you didn't find the data in memcached, try retrieving from the DB
$result = mysqli_query('SELECT * FROM events WHERE id = ' . $id);
// If you found results in the DB...
if ($data = mysqli_fetch_assoc($result)) {
// Save them to memcached for future calls
// Note: here, I'm using the optional param to expire it after 1 day
$m->set('event_' . $id, json_encode($data), 86400);
}
}
// Now you can use your data
var_dump($data);
编辑以在代码中添加注释
关于php - 您将如何在 MVC 项目中缓存内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13497825/