in reply to A singleton wrapper around Cache::Memcached

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.)

Replies are listed 'Best First'.
Re^2: A singleton wrapper around Cache::Memcached
by skx (Parson) on Nov 11, 2005 at 17:15 UTC

    I think in general your approach is probably a better one - especially if there are a significant number of functions that are being proxied. The code you posted seems reasonable to my quick read, and could easily be applied to other wrappers.

    However in this particular case I'm actually doing a little bit more in the forwarding-methods (keeping track of cache hits/misses, and verifying that some state is massaged appropriately).

    I have updated the code here to work properly under strict + warnings, as you are utterly correct about the broken options hash being invalid.

    About your last comment in the method renaming, you are correct. I only changed the names because I'm using a few singletons in my application and every other one uses disconnect - rather than disconnect_all, so it seemed natural to change it to match. On balance leaving its name alone seems best.

    ++ for the feedback.

    Steve
    --