2016-02-13 45 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]; 
});