2 package MooseX::Singleton::Meta::Instance;
4 use Scalar::Util 'weaken';
6 extends 'Moose::Meta::Instance';
8 sub get_singleton_instance {
9 my ($self, $instance) = @_;
11 return $instance if blessed $instance;
13 # optimization: it's really slow to go through new_object for every access
14 # so return the singleton if we see it already exists, which it will every
15 # single except the first.
17 return ${"$instance\::singleton"} if defined ${"$instance\::singleton"};
19 return $instance->meta->construct_instance;
23 my ($self, $instance) = @_;
24 $self->get_singleton_instance($instance);
28 my ($self, $instance, $slot_name) = @_;
29 $self->is_slot_initialized($instance, $slot_name) ? $self->get_singleton_instance($instance)->{$slot_name} : undef;
33 my ($self, $instance, $slot_name, $value) = @_;
34 $self->get_singleton_instance($instance)->{$slot_name} = $value;
37 sub deinitialize_slot {
38 my ( $self, $instance, $slot_name ) = @_;
39 delete $self->get_singleton_instance($instance)->{$slot_name};
42 sub is_slot_initialized {
43 my ($self, $instance, $slot_name, $value) = @_;
44 exists $self->get_singleton_instance($instance)->{$slot_name} ? 1 : 0;
47 sub weaken_slot_value {
48 my ($self, $instance, $slot_name) = @_;
49 weaken $self->get_singleton_instance($instance)->{$slot_name};
52 sub inline_slot_access {
53 my ($self, $instance, $slot_name) = @_;
54 sprintf "%s->meta->instance_metaclass->get_singleton_instance(%s)->{%s}", $instance, $instance, $slot_name;
67 MooseX::Singleton::Meta::Instance
71 This instance metaclass manages attribute access and storage. When accessing an
72 attribute, it will convert a bare package to its cached singleton instance
73 (creating it if necessary).