do not allow double initialization
[gitmo/MooseX-Singleton.git] / lib / MooseX / Singleton / Meta / Class.pm
CommitLineData
109b110b 1#!/usr/bin/env perl
2package MooseX::Singleton::Meta::Class;
3use Moose;
4use MooseX::Singleton::Meta::Instance;
5
6extends 'Moose::Meta::Class';
7
8sub initialize {
9 my $class = shift;
10 my $pkg = shift;
11
12 $class->SUPER::initialize(
13 $pkg,
14 instance_metaclass => 'MooseX::Singleton::Meta::Instance',
15 @_,
16 );
17};
18
1de95613 19sub existing_singleton {
3822ace2 20 my ($class) = @_;
21 my $pkg = $class->name;
22
23 no strict 'refs';
24
25 # create exactly one instance
1de95613 26 if (defined ${"$pkg\::singleton"}) {
27 return ${"$pkg\::singleton"};
3822ace2 28 }
29
1de95613 30 return;
31}
32
33override construct_instance => sub {
34 my ($class) = @_;
35
36 # create exactly one instance
37 my $existing = $class->existing_singleton;
38 return $existing if $existing;
39
40 my $pkg = $class->name;
41 no strict 'refs';
42 return ${"$pkg\::singleton"} = super;
3822ace2 43};
44
109b110b 451;
46
b375b147 47__END__
48
49=pod
50
51=head1 NAME
52
53MooseX::Singleton::Meta::Class
54
55=head1 DESCRIPTION
56
57This metaclass is where the forcing of one instance occurs. The first call to
58C<construct_instance> is run normally (and then cached). Subsequent calls will
59return the cached version.
60
61=cut
62