1 package MooseX::Singleton::Role::Meta::Instance;
3 use Scalar::Util 'weaken';
5 sub get_singleton_instance {
6 my ( $self, $instance ) = @_;
8 return $instance if blessed $instance;
10 # optimization: it's really slow to go through new_object for every access
11 # so return the singleton if we see it already exists, which it will every
12 # single except the first.
14 return ${"$instance\::singleton"} if defined ${"$instance\::singleton"};
16 # We need to go through ->new in order to make sure BUILD and
17 # BUILDARGS get called.
18 return $instance->meta->name->new;
21 override clone_instance => sub {
22 my ( $self, $instance ) = @_;
23 $self->get_singleton_instance($instance);
26 override get_slot_value => sub {
27 my ( $self, $instance, $slot_name ) = @_;
28 $self->is_slot_initialized( $instance, $slot_name )
29 ? $self->get_singleton_instance($instance)->{$slot_name}
33 override set_slot_value => sub {
34 my ( $self, $instance, $slot_name, $value ) = @_;
35 $self->get_singleton_instance($instance)->{$slot_name} = $value;
38 override deinitialize_slot => sub {
39 my ( $self, $instance, $slot_name ) = @_;
40 delete $self->get_singleton_instance($instance)->{$slot_name};
43 override is_slot_initialized => sub {
44 my ( $self, $instance, $slot_name, $value ) = @_;
45 exists $self->get_singleton_instance($instance)->{$slot_name} ? 1 : 0;
48 override weaken_slot_value => sub {
49 my ( $self, $instance, $slot_name ) = @_;
50 weaken $self->get_singleton_instance($instance)->{$slot_name};
53 override inline_slot_access => sub {
54 my ( $self, $instance, $slot_name ) = @_;
55 sprintf "%s->meta->instance_metaclass->get_singleton_instance(%s)->{%s}",
56 $instance, $instance, $slot_name;
69 MooseX::Singleton::Role::Meta::Instance - Instance metaclass role for MooseX::Singleton
73 This role overrides all object access so that it gets the appropriate
74 singleton instance for the class.