1 package MooseX::Singleton::Role::Meta::Class;
3 use MooseX::Singleton::Role::Meta::Instance;
4 use MooseX::Singleton::Role::Meta::Method::Constructor;
7 sub existing_singleton {
9 my $pkg = $class->name;
13 # create exactly one instance
14 if ( defined ${"$pkg\::singleton"} ) {
15 return ${"$pkg\::singleton"};
23 my $pkg = $class->name;
25 undef ${"$pkg\::singleton"};
28 override _construct_instance => sub {
31 # create exactly one instance
32 my $existing = $class->existing_singleton;
33 return $existing if $existing;
35 my $pkg = $class->name;
37 return ${"$pkg\::singleton"} = super;
40 if ( $Moose::VERSION >= 1.9900 ) {
41 override _inline_params => sub {
45 'my $existing = do {',
47 'no warnings "once";',
48 '\${"$class\::singleton"};',
50 'return ${$existing} if ${$existing};',
54 override _inline_extra_init => sub {
57 return '${$existing} = $instance;';
65 # ABSTRACT: Metaclass role for MooseX::Singleton
73 This metaclass role makes sure that there is only ever one instance of an
74 object for a singleton class. The first call to C<construct_instance> is run
75 normally (and then cached). Subsequent calls will return the cached version.