Changes for 0.23
[gitmo/MooseX-Singleton.git] / lib / MooseX / Singleton / Role / Meta / Class.pm
CommitLineData
8eec3c69 1package MooseX::Singleton::Role::Meta::Class;
2use Moose::Role;
a4e5ec1e 3use MooseX::Singleton::Role::Meta::Instance;
4use MooseX::Singleton::Role::Meta::Method::Constructor;
5a0f3fa6 5
724efd93 6our $VERSION = '0.22';
5a0f3fa6 7$VERSION = eval $VERSION;
109b110b 8
1de95613 9sub existing_singleton {
3822ace2 10 my ($class) = @_;
11 my $pkg = $class->name;
12
13 no strict 'refs';
14
15 # create exactly one instance
4c256923 16 if ( defined ${"$pkg\::singleton"} ) {
1de95613 17 return ${"$pkg\::singleton"};
3822ace2 18 }
19
1de95613 20 return;
21}
22
03e1b8df 23sub clear_singleton {
24 my ($class) = @_;
25 my $pkg = $class->name;
26 no strict 'refs';
27 undef ${"$pkg\::singleton"};
28}
29
0cd38a85 30override _construct_instance => sub {
1de95613 31 my ($class) = @_;
32
33 # create exactly one instance
34 my $existing = $class->existing_singleton;
35 return $existing if $existing;
36
37 my $pkg = $class->name;
38 no strict 'refs';
39 return ${"$pkg\::singleton"} = super;
3822ace2 40};
41
2cb90d53 42no Moose::Role;
2b4ce4bd 43
109b110b 441;
45
b375b147 46__END__
47
48=pod
49
50=head1 NAME
51
8eec3c69 52MooseX::Singleton::Role::Meta::Class - Metaclass role for MooseX::Singleton
b375b147 53
54=head1 DESCRIPTION
55
8eec3c69 56This metaclass role makes sure that there is only ever one instance of an
57object for a singleton class. The first call to C<construct_instance> is run
58normally (and then cached). Subsequent calls will return the cached version.
b375b147 59
60=cut
61