2 package # hide the package from PAUSE
10 our $VERSION = '0.04';
12 use base 'Class::MOP::Attribute';
14 sub initialize_instance_slot {
15 my ($self, $instance, $params) = @_;
17 # if the attr has an init_arg, use that, otherwise,
18 # use the attributes name itself as the init_arg
19 my $init_arg = $self->init_arg();
21 if ( exists $params->{$init_arg} ) {
22 my $val = $params->{$init_arg};
23 my $meta_instance = $self->associated_class->get_meta_instance;
24 $meta_instance->set_slot_value_with_init( $instance, $self->slot_name, $val);
28 sub generate_accessor_method {
31 my $slot_name = $attr->slot_name;
32 my $meta_instance = $attr->associated_class->get_meta_instance;
35 if (scalar(@_) == 2) {
36 $meta_instance->set_slot_value_with_init( $_[0], $slot_name, $_[1] );
39 unless ( $meta_instance->slot_initialized( $_[0], $slot_name ) ) {
40 my $value = $attr->has_default ? $attr->default($_[0]) : undef;
41 $meta_instance->set_slot_value_with_init( $_[0], $slot_name, $value );
44 $meta_instance->get_slot_value( $_[0], $slot_name );
49 sub generate_reader_method {
52 my $slot_name = $attr->slot_name;
53 my $meta_instance = $attr->associated_class->get_meta_instance;
56 confess "Cannot assign a value to a read-only accessor" if @_ > 1;
58 unless ( $meta_instance->slot_initialized( $_[0], $slot_name ) ) {
59 my $value = $attr->has_default ? $attr->default($_[0]) : undef;
60 $meta_instance->set_slot_value_with_init( $_[0], $slot_name, $value );
63 $meta_instance->get_slot_value( $_[0], $slot_name );
75 LazyClass - An example metaclass with lazy initialization
81 use metaclass 'Class::MOP::Class' => (
82 ':attribute_metaclass' => 'LazyClass::Attribute'
85 BinaryTree->meta->add_attribute('$:node' => (
90 BinaryTree->meta->add_attribute('$:left' => (
92 default => sub { BinaryTree->new() }
95 BinaryTree->meta->add_attribute('$:right' => (
97 default => sub { BinaryTree->new() }
102 $class->meta->new_object(@_);
107 my $btree = BinaryTree->new();
108 # ... $btree is an empty hash, no keys are initialized yet
112 This is an example metclass in which all attributes are created
113 lazily. This means that no entries are made in the instance HASH
114 until the last possible moment.
116 The example above of a binary tree is a good use for such a
117 metaclass because it allows the class to be space efficient
118 without complicating the programing of it. This would also be
119 ideal for a class which has a large amount of attributes,
120 several of which are optional.
124 Stevan Little E<lt>stevan@iinteractive.comE<gt>
126 =head1 COPYRIGHT AND LICENSE
128 Copyright 2006 by Infinity Interactive, Inc.
130 L<http://www.iinteractive.com>
132 This library is free software; you can redistribute it and/or modify
133 it under the same terms as Perl itself.