Bread::Board::LifeCycle::Singleton - Bread::Board::LifeCycle::Singleton documentation


Bread-Board documentation Contained in the Bread-Board distribution.

Index


Code Index:

NAME

Top

Bread::Board::LifeCycle::Singleton

DESCRIPTION

Top

METHODS

Top

get
instance
has_instance
flush_instance

BUGS

Top

All complex software has bugs lurking in it, and this module is no exception. If you find a bug please either email me, or add the bug to cpan-RT.

AUTHOR

Top

Stevan Little <stevan@iinteractive.com>

COPYRIGHT AND LICENSE

Top


Bread-Board documentation Contained in the Bread-Board distribution.

package Bread::Board::LifeCycle::Singleton;
use Moose::Role;

use Try::Tiny;

with 'Bread::Board::LifeCycle';

our $VERSION   = '0.20';
our $AUTHORITY = 'cpan:STEVAN';

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__