RSS
 

Use memcache better

30 Jun

I believe I have already mentioned a couple of times how memcache makes Grooveshark Lite possible.

Well, while implementing memcache for Grooveshark Lite, I ended up making a wrapper class called GMemcache for lack of a better name, which inherits from the PHP Memcache class, adding on just a few cool enhancements:

1. Singleton. Has static variable $instance that is set in the constructor and is also available in a getInstance() method.
2. Disable-able. Integrating with memcache can involve writing a lot of memcache-specific code, which means it can be quite a pain if you then need to temporarily disable memcache for some reason, such as testing. We define MEMCACHE_DISABLED to true when we wish to have our code bypass memcache altogether. The class wraps get, set, etc., and if memcache is disabled returns false for get (equivalent of saying “I couldn’t find it”) and doesn’t do anything when set is called. otherwise it calls parent::get etc.
3. Version-able. We also define an app version, which is then automatically appended to all keys. That way new releases never get stale data (or worse, data in a different structure from what it expects!). For situations where versioning does not make sense, set, get, etc all take an extra boolean parameter which indicates whether versioning should be skipped (defaults to false).

The nice thing about inheriting from Memcache this way (as opposed to having a Memcache instance as a member variable) is that we don’t have to rewrite all of the functionality. Whatever parts we do not need to change or do not care about, do not have to be written and they will continue to work when accessed via GMemcache.

 
 

Leave a Reply