开发者

CakePHP caching user specific query data, best practice

I would like to employ caching at model level in the current web application I am working on.

I am comfortable with caching general things, like "latest news" or other non-user specific things like that, I am looking for some direction on caching queries which rely on user specific data.

For instance, a list of a User's comments. The query will need the Users ID, and the result will only be specific to that User, so how should I cache this?

More importantly, simply clearing the entire cache when a comment is updated seems very inefficient, it would be nice to get some advice on how to clear user specific cache keys.

Example

function getEntryByInventory($id,$company_id) {
  $getEntryByInventory = Cache::read('Entry.getEntryByInventory.'.$id.'.'.$company_id);
    if($getEntryByInventory !==false) {
        return $getEntryByInventory;
    } else {    
        $getEntryByInventory =  $this->find('first' , array(
            'conditions' => array(
                'Entry.id' => $id, 
                'Inventory.company_id' => $company_id
            )
        ));
        Cache::write('Entry.getEntryByInventory.'.$id.'.'.$company_id , 开发者_开发技巧$getEntryByInventory);
        return $getEntryByInventory;
    }
}

// How would I clear the above cache without knowing the company id?
function beforeSave() {
    Cache::delete('????');
    return true;
}

I can save the result of this query in the cache, and make it specific by adding the $company_id to the cache key, so reading and writing to the cache is fine.

But in this instance, if I needed to delete this key from the cache I would require the $company_id.

My question is, am I going about this the correct way, and if not can I get some pointers please!

Thanks in advance.


Make sure you implement caching last and not first. Once your application works then you can start working on caching specific elements. Some things are just not worth caching (you can't cache all users' comments everywhere). Storage is there for that. Rather work on eliminating the bottlnecks (most of which will be straight forward) before trying to delve into complex caching.


If you use afterSave() function instead of beforeSave() function, the saved data/information will be available in $this->data.

 public function afterSave($created, $options = array()) {
        debug($this->data); // contains id of the modified record
        if ($created) {
            Cache::clear('Entry.getEntryByInventory.'.$this->data['Model']['id'].'.'.$this->data['Model']['company_id']);
        }
    }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜