高效的PHP缓存策略? [重复]

This question already has an answer here:

I am kinda new in the application development. I am developing one application at the moment and I want to know your valueable inputs about a problem that I am facing as a newb.

When it comes to caching, which parts of the application I should add in cache? Let me give you an example of what I am doing:

I am developing a picture sharing application for my users and I have created a cache mechanism to cache every user's data, his albums & his pictures. I currently have 1 query per page (only in case that it is not already stored in Cache) for example:

if ( !$ItemNotInCache )
{
$MyData = $DB->Query('blah');
Cache::CacheIt($MyData);
}

This is about every result I am getting, I am trying not to call too many queries every time a user requests a page, is this efficient? The problem is that as you can understand I had to build this huge mechanism to manipulate all this data in arrays, etc..

  • When a user deletes an image from DB, i have to remove the index from the cached data of his album as well.

  • When a user adds an image to DB, I use array_merge to insert this item to his cached data and so on.

A friend of mine told me that I shouldn't abuse the cache since my data is dynamic and it will change very often and he also told me this is why MySQL is for. My question is I should use the cache in that way or no? As you can understand the data is dynamic and it should be refreshed often. Is this efficient or i should just stick with MySQL queries?

</div>

I think what you are doing is perfectly fine. Retrieving from the cache uses less resources in almost all the cases as opposed to doing a query each time.

However, I wouldn't try to "merge" the added image, just call the database again. Just increment the cache when the album modified. I don't think editing the cache when the album is modified is the right approach. Databases are good at storing and building the data so it's easy to be retrieved. Why do the building yourself?