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, $meta_instance, $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 $meta_instance->set_slot_value($instance, $self->name, $val);
27 sub generate_accessor_method {
30 my $attr_name = $attr->name;
31 my $meta_instance = $attr->associated_class->get_meta_instance;
34 if (scalar(@_) == 2) {
35 $meta_instance->set_slot_value($_[0], $attr_name, $_[1]);
38 unless ( $meta_instance->is_slot_initialized($_[0], $attr_name) ) {
39 my $value = $attr->has_default ? $attr->default($_[0]) : undef;
40 $meta_instance->set_slot_value($_[0], $attr_name, $value);
43 $meta_instance->get_slot_value($_[0], $attr_name);
48 sub generate_reader_method {
51 my $attr_name = $attr->name;
52 my $meta_instance = $attr->associated_class->get_meta_instance;
55 confess "Cannot assign a value to a read-only accessor" if @_ > 1;
57 unless ( $meta_instance->is_slot_initialized($_[0], $attr_name) ) {
58 my $value = $attr->has_default ? $attr->default($_[0]) : undef;
59 $meta_instance->set_slot_value($_[0], $attr_name, $value);
62 $meta_instance->get_slot_value($_[0], $attr_name);
68 package # hide the package from PAUSE
74 our $VERSION = '0.01';
76 use base 'Class::MOP::Instance';
78 sub initialize_all_slots {}
88 LazyClass - An example metaclass with lazy initialization
94 use metaclass 'Class::MOP::Class' => (
95 ':attribute_metaclass' => 'LazyClass::Attribute'
98 BinaryTree->meta->add_attribute('$:node' => (
103 BinaryTree->meta->add_attribute('$:left' => (
105 default => sub { BinaryTree->new() }
108 BinaryTree->meta->add_attribute('$:right' => (
110 default => sub { BinaryTree->new() }
115 $class->meta->new_object(@_);
120 my $btree = BinaryTree->new();
121 # ... $btree is an empty hash, no keys are initialized yet
125 This is an example metclass in which all attributes are created
126 lazily. This means that no entries are made in the instance HASH
127 until the last possible moment.
129 The example above of a binary tree is a good use for such a
130 metaclass because it allows the class to be space efficient
131 without complicating the programing of it. This would also be
132 ideal for a class which has a large amount of attributes,
133 several of which are optional.
137 Stevan Little E<lt>stevan@iinteractive.comE<gt>
139 =head1 COPYRIGHT AND LICENSE
141 Copyright 2006 by Infinity Interactive, Inc.
143 L<http://www.iinteractive.com>
145 This library is free software; you can redistribute it and/or modify
146 it under the same terms as Perl itself.