Re: Singleton per connection

[email protected] (Shlomi Fish)
Newsgroups perl.moose
Message-ID <[email protected]>
Hi Bill,

I'm replying because I didn't see you getting a response in a few days.

On Mon, 9 Apr 2012 17:04:38 +0800
Bill Moseley <[email protected]> wrote:

> We have an in-house storage "backend" we use for a number of purposes.  We
> can pretend it's something like memcached that is configured with host
> names.  I have a role for working with this backend which is consumed by a
> number of more specific classes.  For example, each specific class handles
> decoding and encoding the stored data.
> 
> Often a given application will use a number of these specific classes.  I
> want to use a shared connection in this case.  So, instead of a singleton
> backend class, I want a singleton cached by the config (by the hosts in
> this example).
> 
> 
> my $foo_store = My::Store::Foo->new( { hosts => \@hosts } );
> my $bar_store = My::Store::Bar->new( { hosts => \@hosts } );
> 
> 
> So, $foo_store->backend_connection = $foo_store->backend_connection because
> @hosts are the same in both.
> 
> 
> What I've been doing is something like this in my role:
> 
> has backend_connection => ( builder => _build_connection );
> 
> 
> my %cached_connections;
> 
> sub _build_connection {
>     my $self = shift;
>     return $cached_connection{ $self->connection_key } ||=
> $self->new_connection;
> }
> 
> sub connection_key { return join ':', shift->host_list }
> 
> 
> Does this seem like a reasonable approach?
> 

Yes, pretty much. Maybe I would also make sure that ->host_list is sorted and
uniq’ed or otherwise mostly lacking silly permutations and variations that can
interfere with the caching.

Furthermore, what I normally like to do to implement singletons is create an
"environment" object that contains all the common data, and keep a reference to
it for every class in the system. This way, one can have more than one
environment in the program.

Regards,

	Shlomi Fish

-- 
-----------------------------------------------------------------
Shlomi Fish       http://www.shlomifish.org/
Chuck Norris/etc. Facts - http://www.shlomifish.org/humour/bits/facts/

“Interesting” has a negative correlation with “successful”.
    — Anno on Freenode's #perl

Please reply to list if it's a mailing list post - http://shlom.in/reply .
lmpx.com only provides a reader for public news (NNTP) servers. It is not affiliated with the servers or forums shown here and is not responsible for the content of articles, which is written by their respective authors.