Commit | Line | Data |
---|---|---|
8eec3c69 | 1 | package MooseX::Singleton::Role::Meta::Class; |
2 | use Moose::Role; | |
a4e5ec1e | 3 | use MooseX::Singleton::Role::Meta::Instance; |
4 | use MooseX::Singleton::Role::Meta::Method::Constructor; | |
5a0f3fa6 | 5 | |
724efd93 | 6 | our $VERSION = '0.22'; |
5a0f3fa6 | 7 | $VERSION = eval $VERSION; |
109b110b | 8 | |
1de95613 | 9 | sub 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 | 23 | sub clear_singleton { |
24 | my ($class) = @_; | |
25 | my $pkg = $class->name; | |
26 | no strict 'refs'; | |
27 | undef ${"$pkg\::singleton"}; | |
28 | } | |
29 | ||
0cd38a85 | 30 | override _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 | 42 | no Moose::Role; |
2b4ce4bd | 43 | |
109b110b | 44 | 1; |
45 | ||
b375b147 | 46 | __END__ |
47 | ||
48 | =pod | |
49 | ||
50 | =head1 NAME | |
51 | ||
8eec3c69 | 52 | MooseX::Singleton::Role::Meta::Class - Metaclass role for MooseX::Singleton |
b375b147 | 53 | |
54 | =head1 DESCRIPTION | |
55 | ||
8eec3c69 | 56 | This metaclass role makes sure that there is only ever one instance of an |
57 | object for a singleton class. The first call to C<construct_instance> is run | |
58 | normally (and then cached). Subsequent calls will return the cached version. | |
b375b147 | 59 | |
60 | =cut | |
61 |