Bread-Board
view release on metacpan or search on metacpan
lib/Bread/Board/LifeCycle/Singleton.pm view on Meta::CPAN
package Bread::Board::LifeCycle::Singleton;
our $AUTHORITY = 'cpan:STEVAN';
# ABSTRACT: service role for singleton lifecycle
$Bread::Board::LifeCycle::Singleton::VERSION = '0.37';
use Moose::Role;
use Try::Tiny;
with 'Bread::Board::LifeCycle';
has 'instance' => (
traits => [ 'NoClone' ],
is => 'rw',
isa => 'Any',
predicate => 'has_instance',
clearer => 'flush_instance'
);
has 'resolving_singleton' => (
traits => [ 'NoClone' ],
is => 'rw',
isa => 'Bool',
default => 0,
);
around 'get' => sub {
my $next = shift;
my $self = shift;
# return it if we got it ...
return $self->instance if $self->has_instance;
my $instance;
if ($self->resolving_singleton) {
$instance = Bread::Board::Service::Deferred->new(service => $self);
}
else {
$self->resolving_singleton(1);
my @args = @_;
try {
# otherwise fetch it ...
$instance = $self->$next(@args);
}
catch {
die $_;
}
finally {
$self->resolving_singleton(0);
};
}
# if we get a copy, and our copy
# has not already been set ...
$self->instance($instance);
# return whatever we have ...
return $self->instance;
};
no Moose::Role; 1;
__END__
=pod
=encoding UTF-8
( run in 0.638 second using v1.01-cache-2.11-cpan-39bf76dae61 )