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 | |
109b110b |
6 | |
1de95613 |
7 | sub existing_singleton { |
3822ace2 |
8 | my ($class) = @_; |
9 | my $pkg = $class->name; |
10 | |
11 | no strict 'refs'; |
12 | |
13 | # create exactly one instance |
4c256923 |
14 | if ( defined ${"$pkg\::singleton"} ) { |
1de95613 |
15 | return ${"$pkg\::singleton"}; |
3822ace2 |
16 | } |
17 | |
1de95613 |
18 | return; |
19 | } |
20 | |
03e1b8df |
21 | sub clear_singleton { |
22 | my ($class) = @_; |
23 | my $pkg = $class->name; |
24 | no strict 'refs'; |
25 | undef ${"$pkg\::singleton"}; |
26 | } |
27 | |
0cd38a85 |
28 | override _construct_instance => sub { |
1de95613 |
29 | my ($class) = @_; |
30 | |
31 | # create exactly one instance |
32 | my $existing = $class->existing_singleton; |
33 | return $existing if $existing; |
34 | |
35 | my $pkg = $class->name; |
36 | no strict 'refs'; |
0f22810a |
37 | no warnings 'once'; |
1de95613 |
38 | return ${"$pkg\::singleton"} = super; |
3822ace2 |
39 | }; |
40 | |
837c9793 |
41 | if ( $Moose::VERSION >= 1.9900 ) { |
42 | override _inline_params => sub { |
43 | my $self = shift; |
44 | |
45 | return |
46 | 'my $existing = do {', |
47 | 'no strict "refs";', |
48 | 'no warnings "once";', |
49 | '\${"$class\::singleton"};', |
50 | '};', |
51 | 'return ${$existing} if ${$existing};', |
52 | super(); |
53 | }; |
54 | |
55 | override _inline_extra_init => sub { |
56 | my $self = shift; |
57 | |
58 | return '${$existing} = $instance;'; |
59 | }; |
60 | } |
61 | |
2cb90d53 |
62 | no Moose::Role; |
2b4ce4bd |
63 | |
109b110b |
64 | 1; |
65 | |
4e4f795a |
66 | # ABSTRACT: Metaclass role for MooseX::Singleton |
67 | |
b375b147 |
68 | __END__ |
69 | |
70 | =pod |
71 | |
b375b147 |
72 | =head1 DESCRIPTION |
73 | |
8eec3c69 |
74 | This metaclass role makes sure that there is only ever one instance of an |
75 | object for a singleton class. The first call to C<construct_instance> is run |
76 | normally (and then cached). Subsequent calls will return the cached version. |
b375b147 |
77 | |
78 | =cut |
79 | |