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!