【问题标题】:Where do cache calls go in MVC缓存调用在 MVC 中的位置
【发布时间】:2016-02-13 22:33:15
【问题描述】:

所以我将 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);

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

【问题讨论】:

    标签: php caching redis predis


    【解决方案1】:

    您应该首先分析您的应用程序并找出最常调用的部分和最慢的部分。

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

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

    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];
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-09-25
      • 2017-10-03
      • 2012-04-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多