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?
--
Bill Moseley
[email protected]