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;
38 return ${"$pkg\::singleton"} = super;
41 if ( $Moose::VERSION >= 1.9900 ) {
42 override _inline_params => sub {
46 'my $existing = do {',
48 'no warnings "once";',
49 '\${"$class\::singleton"};',
51 'return ${$existing} if ${$existing};',
55 override _inline_extra_init => sub {
58 return '${$existing} = $instance;';
66 # ABSTRACT: Metaclass role for MooseX::Singleton
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.