2013-12-11 11:11

PHP memcached更新结果


I'm about to implement a memcached class which can be extended by our database class. However i have looked at many different ways of doing this.

My First question was, what is the point in the Memcached::set() as it seems to replace the value of the key. Does this not defeat the object of caching your results?

My Second question was, technically speaking what is the fastest/best way to update the value of a key without checking the results every time the query is executed. If this happens, the results been retreived would have to be checked constantly so there would be no point in caching as the results would constantly be connecting to the mysql database.

Lastly, What is the best way of creating a key? most people recommend using MD5 however using MD5 on a PDO query would be the same regardless.


$key = MD5("SELECT * FROM test WHERE category=?");

the category could produce many different results however the key would be constantly replaced. Is there a best practice for this?

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答


  • dongmi5015 dongmi5015 8年前

    You set a cache entry when you had to read the database, so that next time, you don't have to read the database first. You'd check the cache, and if it was not there, or otherwise out of date, then you fall back to the database read, and reset the key.

    As for a key name, it depends very much on the expected values of the category. If if was a simple integer, or string, I'd use a key like test.category:99 or test.category:car. If it was likely to be more, it may be useful to encode it, so there were no spaces in it (say, urlencode).

    Finally, if it were any more complex than that - test:category:{MD5(category)}.

    Since the key is only a reference to the data and you'll never be using it in any kind of SQL query, putting the value in there is not generally going to be a security issue.

    Since you control when the cache is set, if the underlying database entry is changed, it's simple to also update the cache with the new data at the same time - you just have to use the same key.

    点赞 评论 复制链接分享