2016-02-13 43 views
0

因此,我将Redis添加到已开发的项目中,并且想知道在哪里放置这些缓存调用。 有现有的模式,我想知道如果我可以注入的Redis到模型,然后用包缓存代码每个查询,像这样:高速缓存调用在MVC中的位置

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

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

回答

0

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

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

我个人认为缓存:: 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]; 
});