缓存调用在MVC中的位置

时间:2016-02-13 22:33:16

标签: php caching redis predis

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

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

1 个答案:

答案 0 :(得分:0)

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

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

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

./bin/kafka-run-class.sh kafka.tools.GetOffsetShell 
  --broker-list <broker>:  <port> 
  --topic <topic-name> --time -1 --offsets 1 
  | awk -F  ":" '{sum += $3} END {print sum}'

现在你的代码看起来像:

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