Simon ([personal profile] swaldman) wrote in [site community profile] dw_dev_training2012-12-23 03:39 pm
Entry tags:

Using memcache

This is the first time I've tried using memcache, so I thought I'd post here and check I'm doing it right.
This is perhaps a slightly unusual application, because it isn't for caching something that's in the db.

Scenario: There is a Twitter config variable that we need to know, which changes occasionally. There's a Twitter API call to find it out, but they ask that people don't call this more than once a day. So, my intention is along these lines:

#allow an override, and also a fallback for sites that don't use memcache.
return $LJ::MYVARIABLE if $LJ::MYVARIABLE

my $value = LJ::MemCache::get( 'mykey' );
return $value if $value;

#we clearly don't have it at present
#Do stuff to get the value from Twitter.

LJ::MemCache::set( 'mykey', $value, 24*60*60 );
return $value;


So, does the above make sense? Am I doing things correctly? Is there a convention as to what the key should be called?

Thanks :-)
exor674: Computer Science is my girlfriend (Default)

[personal profile] exor674 2012-12-23 08:38 pm (UTC)(link)
How often does this variable change? and is this "everything breaks if the variable isn't set correctly"?

I don't think there's really a convention, just try not to avoid conflicts, so something like 'twitter:supermagic' or something would work ( but, uh, descriptive )
But generally that looks right.
Edited 2012-12-23 20:38 (UTC)
mark: A photo of Mark kneeling on top of the Taal Volcano in the Philippines. It was a long hike. (Default)

[staff profile] mark 2012-12-24 12:18 am (UTC)(link)
A small thing: usually you want to use "defined" instead of "truthiness" on configuration items. I don't know what $LJ::MYVARIABLE contains, but if it ever contained a 0 or 'false' or similar, it would cause you to hit Twitter a lot.