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) ? $self->get_singleton_instance($instance)->{$slot_name} : undef;
31 override set_slot_value => sub {
32 my ($self, $instance, $slot_name, $value) = @_;
33 $self->get_singleton_instance($instance)->{$slot_name} = $value;
36 override deinitialize_slot => sub {
37 my ( $self, $instance, $slot_name ) = @_;
38 delete $self->get_singleton_instance($instance)->{$slot_name};
41 override is_slot_initialized => sub {
42 my ($self, $instance, $slot_name, $value) = @_;
43 exists $self->get_singleton_instance($instance)->{$slot_name} ? 1 : 0;
46 override weaken_slot_value => sub {
47 my ($self, $instance, $slot_name) = @_;
48 weaken $self->get_singleton_instance($instance)->{$slot_name};
51 override inline_slot_access => sub {
52 my ($self, $instance, $slot_name) = @_;
53 sprintf "%s->meta->instance_metaclass->get_singleton_instance(%s)->{%s}", $instance, $instance, $slot_name;
66 MooseX::Singleton::Role::Meta::Instance - Instance metaclass role for MooseX::Singleton
70 This role overrides all object access so that it gets the appropriate
71 singleton instance for the class.