1 package MooseX::Singleton;
5 use MooseX::Singleton::Object;
6 use MooseX::Singleton::Meta::Class;
9 $VERSION = eval $VERSION;
11 Moose::Exporter->setup_import_methods( also => 'Moose' );
19 my $caller = $p{for_class};
21 Moose::Util::MetaRole::apply_metaclass_roles(
23 metaclass_roles => ['MooseX::Singleton::Role::Meta::Class'],
24 instance_metaclass_roles =>
25 ['MooseX::Singleton::Role::Meta::Instance'],
26 constructor_class_roles =>
27 ['MooseX::Singleton::Role::Meta::Method::Constructor'],
30 Moose::Util::MetaRole::apply_base_class_roles(
33 ['MooseX::Singleton::Role::Object'],
36 return $caller->meta();
48 MooseX::Singleton - turn your Moose class into a singleton
53 use MooseX::Singleton;
57 isa => 'HashRef[Str]',
58 default => sub { \%ENV },
63 delete MyApp->env->{PATH};
64 my $instance = MyApp->instance;
65 my $same = MyApp->instance;
69 A singleton is a class that has only one instance in an application.
70 C<MooseX::Singleton> lets you easily upgrade (or downgrade, as it were) your
71 L<Moose> class to a singleton.
73 All you should need to do to transform your class is to change C<use Moose> to
74 C<use MooseX::Singleton>. This module uses a new class metaclass and instance
75 metaclass, so if you're doing metamagic you may not be able to use this.
77 C<MooseX::Singleton> gives your class an C<instance> method that can be used to
78 get a handle on the singleton. It's actually just an alias for C<new>.
80 Alternatively, C<< YourPackage->method >> should just work. This includes
83 If you need to reset your class's singleton object for some reason (e.g.
84 tests), you can call C<< YourPackage->_clear_instance >>.
90 =item Always more tests and doc
94 C<instance> invokes C<new> every time C<< Package->method >> is called, which
95 incurs a nontrivial runtime cost. I've implemented a short-circuit for this
96 case, which does eliminate nearly all of the runtime cost. However, it's ugly
97 and should be fixed in a more elegant way.
103 All complex software has bugs lurking in it, and this module is no
104 exception. If you find a bug please either email me, or add the bug
109 Shawn M Moore E<lt>sartak@gmail.comE<gt>
111 Dave Rolsky E<lt>autarch@urth.orgE<gt>
113 =head1 SOME CODE STOLEN FROM
115 Anders Nor Berle E<lt>debolaz@gmail.comE<gt>
117 =head1 AND PATCHES FROM
119 Ricardo SIGNES E<lt>rjbs@cpan.orgE<gt>
121 =head1 COPYRIGHT AND LICENSE
123 Copyright 2007, 2008 Infinity Interactive
125 This program is free software; you can redistribute it and/or modify it under
126 the same terms as Perl itself.