I needed to implement some cacheing on a website I was developing and looked around for some PHP solutions to cache the data I was generating from multiple different sql queries per page. Memcache was an obvious solution but I could not find anything that fitted nicely with my existing PHP code. Ideally I just wanted to take existing sql queries and convert them to use, where available the memcache cache, and where not available to simply query the database.
Having spent a day or so Googling around I developed a memcache php wrapper class that I can use in conjunction with my existing database classes.
The memcache class can be used standalone for normal cacheing of data, but in conjunction with the DB wrapper it is allows you to simply pass a query to a function that returns all rows in an array either via the database or the memcached cache. You can decide manually if you want to query via memcache or directly, you can also simply switch memcache off or on as required. The process is failsafe, if the memcache server dies then queries automatically will stop using memcache and use the database.
The memcache wrapper implements name space and name space versioning to manage the memcache data keys. The name space represents your data set. A name space version is stored in the memcache and by simply incrementing the version number of the name space for your data, you change the name of the current dataset namespace key which invalidates the cache and forces a new cached data set entry to be created. Old keys will be deleted as they expire. You can see this process in action using the live demo below. My default TTL is currently set at 5 minutes. Note whether the data comes from the cache or the database, refresh the data or increment the name space key version to see how new keys are created.
I am still monitoring this implementation to ensure the cache is working as expected, it is clearly faster for some pages where I was returning large rows of fairly static data from the database to populate the page. However one must be careful to only cache where required, not all queries will benefit from being cached. You must remember to increment the name space key version whenever you update a table represented by the namespace, otherwise you will only see cached data! It is also important to ensure that the TTL for the key holding the name space version is longer than that of your actual data keys in the demo I set the keys used to hold version numbers to expire after 30 days.
This version is using the memcache api and not memcached. And I do also realise it is bad practise to still be using Mysql for new developments and I will be migrating my sql code to a new api ASAP I promise…
Any comments on the approach to using memcache to cache db queries developed here would be more than welcome.
You can download the code and classes used to create the demo below here.