缓存调用在 MVC 中的去向


Where do cache calls go in MVC

所以我正在将 Redis 添加到一个已经开发的项目中,我想知道将这些缓存调用放在哪里。有现有的模型,我想知道我是否可以将 redis 注入到模型中,然后用缓存代码包装每个查询,如下所示:

$cacheKey = "table/{$id}";
// If table entity is not in cache
if (!$predis->exists($cacheKey)) {
    // Pre-existing database code
    $this->db->query('SELECT * FROM table WHERE table.id = "'.$id.'" ');
    $query = $this->db->get();
    $result = $query->result_array();
    // Set entity in redis cache
    $predis->set($cacheKey, json_encode($result[0]));
    return $result[0];
}
// Return cached entity from redis
return json_decode($predis->get($cacheKey), true);

但我只是想知道这是否是一个肮脏的黑客,或者实际上是最好的做事方式,它是放置缓存代码的最合适地方吗?我从以前的项目中了解到,最好在第一次就以正确的方式做事!

您应该首先分析应用程序,并找出哪些部分最常调用,哪些部分最慢。

如果缓存整个 HTML 部分而不是单个数据库行,将获得最佳结果。(http://kiss-web.blogspot.com/2016/02/memcached-vs-redisphpredis-vs-predis-vs.html(。

我个人认为 Cache::Remember 是最好的模式:

class Cache {
    protected $connection;
    public function __construct($options) {
        $this->connection = new Client($options);
    }
    public function remember($key, $closure, $expiration = 86400) {
        $result = $this->connection->get($key);
        if($result!==false) {
            return unserialize($result);
        }
        $result = $closure();
        $this->connection->set($key, serialize($result), 'ex', $expiration);
        return $result;
    }
}

现在,您的代码如下所示:

$cacheKey = "table/{$id}";
return $cache->remember($cacheKey, function() use ($id) {
    $this->db->query('SELECT * FROM table WHERE table.id = "'.$id.'" ');
    $query = $this->db->get();
    $result = $query->result_array();
    return $result[0];
});