1 package MooseX::Singleton;
5 use MooseX::Singleton::Role::Object;
6 use MooseX::Singleton::Role::Meta::Class;
7 use MooseX::Singleton::Role::Meta::Instance;
10 Moose::Exporter->setup_import_methods( also => 'Moose' );
18 my $caller = $p{for_class};
20 Moose::Util::MetaRole::apply_metaroles(
23 class => ['MooseX::Singleton::Role::Meta::Class'],
25 ['MooseX::Singleton::Role::Meta::Instance'],
27 ['MooseX::Singleton::Role::Meta::Method::Constructor'],
31 Moose::Util::MetaRole::apply_base_class_roles(
34 ['MooseX::Singleton::Role::Object'],
37 return $caller->meta();
43 # ABSTRACT: turn your Moose class into a singleton
52 use MooseX::Singleton;
56 isa => 'HashRef[Str]',
57 default => sub { \%ENV },
62 delete MyApp->env->{PATH};
63 my $instance = MyApp->instance;
64 my $same = MyApp->instance;
68 A singleton is a class that has only one instance in an application.
69 C<MooseX::Singleton> lets you easily upgrade (or downgrade, as it were) your
70 L<Moose> class to a singleton.
72 All you should need to do to transform your class is to change C<use Moose> to
73 C<use MooseX::Singleton>. This module uses metaclass roles to do its magic, so
74 it should cooperate with most other C<MooseX> modules.
78 A singleton class will have the following additional methods:
80 =head2 Singleton->instance
82 This returns the singleton instance for the given package. This method does
83 I<not> accept any arguments. If the instance does not yet exist, it is created
84 with its defaults values. This means that if your singleton requires
85 arguments, calling C<instance> will die if the object has not already been
88 =head2 Singleton->initialize(%args)
90 This method can be called I<only once per class>. It explicitly initializes
91 the singleton object with the given arguments.
93 =head2 Singleton->_clear_instance
95 This clears the existing singleton instance for the class. Obviously, this is
96 meant for use only inside the class itself.
100 This method currently works like a hybrid of C<initialize> and
101 C<instance>. However, calling C<new> directly will probably be deprecated in a
102 future release. Instead, call C<initialize> or C<instance> as appropriate.
106 Please report any bugs or feature requests to
107 C<bug-moosex-singleton@rt.cpan.org>, or through the web interface at
108 L<http://rt.cpan.org>. We will be notified, and then you'll automatically be
109 notified of progress on your bug as we make changes.
111 =head1 SOME CODE STOLEN FROM
113 Anders Nor Berle E<lt>debolaz@gmail.comE<gt>
115 =head1 AND PATCHES FROM
117 Ricardo SIGNES E<lt>rjbs@cpan.orgE<gt>