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 $self->associated_class
25 ->set_slot_value($instance, $self->name, $val);
29 sub generate_accessor_method {
32 my $attr_name = $attr->name;
33 my $meta_instance = $attr->associated_class->get_meta_instance;
36 if (scalar(@_) == 2) {
37 $meta_instance->set_slot_value($_[0], $attr_name, $_[1]);
40 unless ( $meta_instance->is_slot_initialized($_[0], $attr_name) ) {
41 my $value = $attr->has_default ? $attr->default($_[0]) : undef;
42 $meta_instance->set_slot_value($_[0], $attr_name, $value);
45 $meta_instance->get_slot_value($_[0], $attr_name);
50 sub generate_reader_method {
53 my $attr_name = $attr->name;
54 my $meta_instance = $attr->associated_class->get_meta_instance;
57 confess "Cannot assign a value to a read-only accessor" if @_ > 1;
59 unless ( $meta_instance->is_slot_initialized($_[0], $attr_name) ) {
60 my $value = $attr->has_default ? $attr->default($_[0]) : undef;
61 $meta_instance->set_slot_value($_[0], $attr_name, $value);
64 $meta_instance->get_slot_value($_[0], $attr_name);
70 package # hide the package from PAUSE
76 our $VERSION = '0.01';
78 use base 'Class::MOP::Instance';
80 sub initialize_all_slots {}
90 LazyClass - An example metaclass with lazy initialization
96 use metaclass 'Class::MOP::Class' => (
97 ':attribute_metaclass' => 'LazyClass::Attribute'
100 BinaryTree->meta->add_attribute('$:node' => (
105 BinaryTree->meta->add_attribute('$:left' => (
107 default => sub { BinaryTree->new() }
110 BinaryTree->meta->add_attribute('$:right' => (
112 default => sub { BinaryTree->new() }
117 $class->meta->new_object(@_);
122 my $btree = BinaryTree->new();
123 # ... $btree is an empty hash, no keys are initialized yet
127 This is an example metclass in which all attributes are created
128 lazily. This means that no entries are made in the instance HASH
129 until the last possible moment.
131 The example above of a binary tree is a good use for such a
132 metaclass because it allows the class to be space efficient
133 without complicating the programing of it. This would also be
134 ideal for a class which has a large amount of attributes,
135 several of which are optional.
139 Stevan Little E<lt>stevan@iinteractive.comE<gt>
141 =head1 COPYRIGHT AND LICENSE
143 Copyright 2006 by Infinity Interactive, Inc.
145 L<http://www.iinteractive.com>
147 This library is free software; you can redistribute it and/or modify
148 it under the same terms as Perl itself.