1 package MooseX::Singleton::Role::Meta::Instance;
3 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 )
30 ? $self->get_singleton_instance($instance)->{$slot_name}
34 override set_slot_value => sub {
35 my ( $self, $instance, $slot_name, $value ) = @_;
36 $self->get_singleton_instance($instance)->{$slot_name} = $value;
39 override deinitialize_slot => sub {
40 my ( $self, $instance, $slot_name ) = @_;
41 delete $self->get_singleton_instance($instance)->{$slot_name};
44 override is_slot_initialized => sub {
45 my ( $self, $instance, $slot_name, $value ) = @_;
46 exists $self->get_singleton_instance($instance)->{$slot_name} ? 1 : 0;
49 override weaken_slot_value => sub {
50 my ( $self, $instance, $slot_name ) = @_;
51 weaken $self->get_singleton_instance($instance)->{$slot_name};
54 override inline_slot_access => sub {
55 my ( $self, $instance, $slot_name ) = @_;
56 sprintf "%s->meta->instance_metaclass->get_singleton_instance(%s)->{%s}",
57 $instance, $instance, $slot_name;
64 # ABSTRACT: Instance metaclass role for MooseX::Singleton
72 This role overrides all object access so that it gets the appropriate
73 singleton instance for the class.