I'm kinda curious... wouldn't it be easier if your instance() method returned either the real Cache::MemCached object, if that package is available, or a reference to an object of your package if Cache::MemCached is not available? Then you could have an AUTOLOAD that simply did nothing to overload all functions to, well, do nothing, and that would be your degredation.
I'm also curious as to whether you tested this (with warnings/strict) - just looking at it, I'm not sure where the get/set/delete functions are getting their %options hash from. There is a declared %options hash inside new, but it's a lexical which doesn't seem like it should get out from that sub (I'm not seeing this to be a closure).
Finally, I wouldn't change function names in a wrapper: disconnect shouldn't call disconnect_all. It should be called disconnect_all if it calls disconnect_all. That makes the transfer easier.
package Singleton::MemCache;
use strict;
use warnings;
{
my $_cache;
sub instance { $_cache ||= (shift)->new() }
}
sub new
{
my $class = shift;
# see if we're enabled.
eval {
require Cache::Memcached;
my $cache = Cache::Memcached->new({
servers => [ 'localhost:11211' ],
});
return $cache;
};
# we aren't.
return bless {}, $class;
}
sub AUTOLOAD { wantarray ? () : undef }
1;
Completely untested, but that's probably closer to what you want. (Note: I did like the instance sub - very nice. I had never thought of doing it that way. Thanks ;-})
It's also faster (because there is one less sub in between the code that's trying to cache stuff and the code that is doing the caching). And we got rid of that evil eval STRING.
(I also got rid of all that nice documentation, but that's because I was just typing this off the top of my head - all your original documentation should continue to hold here, except for that disconnect function - it becomes disconnect_all.) |