问题
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.
回答1:
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.
回答2:
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']);
}
}
来源:https://stackoverflow.com/questions/5886359/cakephp-caching-user-specific-query-data-best-practice