0

I want to implement a cache functionnality for cakephp 2.5.3, related to find queries, but I want to invalidate cache on all events related to the tables (update, delete, ...). I coded this into AppModel.php, can you tell me what do you think about the code logic and efficiency ? Thanks.

public function find($conditions = null, $fields = array(), $order = null, $recursive = null) {
    $keyName = sha1(serialize(func_get_args()));
    if (Cache::read($this->table . '_' . $keyName, '5m') !== false) {
        $this->log('read cache ' . $this->table . '_' . $keyName);

        return Cache::read($this->table . '_' . $keyName, '5m');
    } else {

        $data = parent::find($conditions, $fields, $order, $recursive);
        Cache::write($this->table . '_' . $keyName, $data, '5m');
        $this->addToCacheList($keyName);
        $this->log('add ' . $this->table . '_' . $keyName);

        return $data;
    }
}

public function afterSave($created, $options = array()) {

    $this->flushCacheList();

    parent::afterSave($created, $options);
}

public function afterDelete() {

    $this->flushCacheList();

    parent::afterDelete();
}

public function addToCacheList($keyName) {
    if (Cache::read($this->table, '5m') !== false) {
        $values = Cache::read($this->table, '5m');
        $values[] = $keyName;
    } else {
        $values = array($keyName);
    }

    Cache::write($this->table, $values, '5m');
}

public function flushCacheList() {
    if (Cache::read($this->table, '5m')) {
        $values = Cache::read($this->table, '5m');
        foreach($values AS $value) {
            Cache::delete($this->table . '_' . $value, '5m');
            $this->log('flush ' . $this->table . '_' . $value);
        }
        Cache::delete($this->table, '5m');
    }
}
tereško
  • 58,060
  • 25
  • 98
  • 150
zeflex
  • 1,487
  • 1
  • 14
  • 29

1 Answers1

0

CakePHP has already a built in query cache.

what do you think about the code logic and efficiency ?

I'm not sure but I think you flush the cache too often to be efficient.

Don't think about performance benchmark it. The only reliable way is a benchmark.

But I would say cache the results of queries instead.

floriank
  • 25,546
  • 9
  • 42
  • 66
  • I saw http://book.cakephp.org/2.0/en/core-libraries/caching.html#using-cache-to-store-common-query-results but there, you are not invalidating the cache on update/save/delete operations. That's why I implemented this as I didn't find something similar. When you say I flush the cache too often, I will tell yes and no. I want to get the freshest results available after any operations on any table. – zeflex Jan 08 '15 at 15:48