2 package MooseX::Singleton::Role::Meta::Instance;
4 use Scalar::Util 'weaken';
6 sub get_singleton_instance {
7 my ($self, $instance) = @_;
9 return $instance if blessed $instance;
11 # optimization: it's really slow to go through new_object for every access
12 # so return the singleton if we see it already exists, which it will every
13 # single except the first.
15 return ${"$instance\::singleton"} if defined ${"$instance\::singleton"};
17 # We need to go through ->new in order to make sure BUILD and
18 # BUILDARGS get called.
19 return $instance->meta->name->new;
22 override clone_instance => sub {
23 my ($self, $instance) = @_;
24 $self->get_singleton_instance($instance);
27 override get_slot_value => sub {
28 my ($self, $instance, $slot_name) = @_;
29 $self->is_slot_initialized($instance, $slot_name) ? $self->get_singleton_instance($instance)->{$slot_name} : undef;
32 override set_slot_value => sub {
33 my ($self, $instance, $slot_name, $value) = @_;
34 $self->get_singleton_instance($instance)->{$slot_name} = $value;
37 override deinitialize_slot => sub {
38 my ( $self, $instance, $slot_name ) = @_;
39 delete $self->get_singleton_instance($instance)->{$slot_name};
42 override is_slot_initialized => sub {
43 my ($self, $instance, $slot_name, $value) = @_;
44 exists $self->get_singleton_instance($instance)->{$slot_name} ? 1 : 0;
47 override weaken_slot_value => sub {
48 my ($self, $instance, $slot_name) = @_;
49 weaken $self->get_singleton_instance($instance)->{$slot_name};
52 override inline_slot_access => sub {
53 my ($self, $instance, $slot_name) = @_;
54 sprintf "%s->meta->instance_metaclass->get_singleton_instance(%s)->{%s}", $instance, $instance, $slot_name;
67 MooseX::Singleton::Role::Meta::Instance - Instance metaclass role for MooseX::Singleton
71 This role overrides all object access so that it gets the appropriate
72 singleton instance for the class.