php - 您将如何在 MVC 项目中缓存内容

标签 php model-view-controller caching

我有一个项目是几个体育赛事系列的结果数据库。 正如您想象的那样,大多数内容或多或少保持不变。 我想缓存一些内容以保存数据库查询。

该项目是使用 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/

相关文章:

caching - 将 Redis 与 Laravel : Do I use the Cache driver, 或 Redis 类一起使用?

java - 如何避免 JBoss-Cache 区域被驱逐?

php - APC 无法区分多个 symfony 站点

php - 将表单中 "on"的所有值更改为 "Yes"

javascript - Backbone-relational 不能实例化两个 RelationalModel 对象

model-view-controller - 在 MVC 中 - session 处理和身份验证是否由用户模型处理?

java - Abstract Dao 未使用 Hibernate 更新或保存

php - PhpStorm 中带有 Vagrant 和 Xdebug 的恼人警告 "Debug session was finished without being paused"

php - Laravel 特定路由及其子路由的全局范围

php - 我无法回显变量,但我可以在函数中使用它吗?