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

Related posts

Recent Viewed