0

So I'm adding Redis to an already developed project and I'm wondering where exactly to put these cache calls. There are existing models, and I am wondering if I can just inject redis into the models and then wrap each query with cache code, like this:

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

But I'm just wondering if this is a dirty hack, or in fact the best way of doing things, and is it the most appropriate place to put the cache code? I've learned from previous projects that it's better to do things the right way, the first time around!

Donal.Lynch.Msc
  • 3,365
  • 12
  • 48
  • 78

1 Answers1

0

You should start with profiling your application first and finding which parts are most often called and which are slowest.

You will get best result if you cache whole HTML parts, not single database rows. ( http://kiss-web.blogspot.com/2016/02/memcached-vs-redisphpredis-vs-predis-vs.html ).

Personally I think that Cache::remeber is best pattern:

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

Now your code would look like:

$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];
});
my-nick
  • 691
  • 1
  • 5
  • 11