您将如何在MVC项目中缓存内容 [英] How would you cache content in an MVC project

查看:69
本文介绍了您将如何在MVC项目中缓存内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a project that is a results database for several sport event series. As you an imagine most the content remains more or less the same. I would like to cache some of the content to save database queries.

该项目是使用PHP构建的,并且使用的是自定义MVC. 您将在哪里添加缓存逻辑?

The project is build using PHP and is using a custom MVC. Where would you add the caching logic?

推荐答案

使用Memcached.诸如此类,您可以在其中缓存查询结果,然后尝试在DB之前从缓存中检索.

Use Memcached. Something like this, where you cache the results of the query, and try retrieving from cache before DB.

添加了对数据进行json_encoding ... json_encode比PHP对数组的默认序列化稍快,并且可以供访问数据的其他应用程序使用

Added json_encoding the data... json_encode is slightly faster than PHP's default serialization for arrays, and can be used by other applications accessing the data

默认情况下,Memcached使用FastLZ压缩.

Memcached by default uses FastLZ compression.

// 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);

编辑后可在代码中添加注释

Edited to add comments in code

这篇关于您将如何在MVC项目中缓存内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆