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, $class, $meta_instance, $params) = @_;
16 # if the attr has an init_arg, use that, otherwise,
17 # use the attributes name itself as the init_arg
18 my $init_arg = $self->init_arg();
19 # try to fetch the init arg from the %params ...
21 $val = $params->{$init_arg} if exists $params->{$init_arg};
22 # now add this to the instance structure
23 # only if we have found a value at all
24 $meta_instance->add_slot($self->name, $val) if defined $val;
28 sub generate_accessor_method {
29 my ($self, $attr_name) = @_;
31 if (scalar(@_) == 2) {
32 $_[0]->{$attr_name} = $_[1];
35 if (!exists $_[0]->{$attr_name}) {
36 my $attr = $self->associated_class->get_attribute($attr_name);
37 $_[0]->{$attr_name} = $attr->has_default ? $attr->default($_[0]) : undef;
44 sub generate_reader_method {
45 my ($self, $attr_name) = @_;
47 confess "Cannot assign a value to a read-only accessor" if @_ > 1;
48 if (!exists $_[0]->{$attr_name}) {
49 my $attr = $self->associated_class->get_attribute($attr_name);
50 $_[0]->{$attr_name} = $attr->has_default ? $attr->default($_[0]) : undef;
64 LazyClass - An example metaclass with lazy initialization
70 use metaclass 'Class::MOP::Class' => (
71 ':attribute_metaclass' => 'LazyClass::Attribute'
74 BinaryTree->meta->add_attribute('$:node' => (
79 BinaryTree->meta->add_attribute('$:left' => (
81 default => sub { BinaryTree->new() }
84 BinaryTree->meta->add_attribute('$:right' => (
86 default => sub { BinaryTree->new() }
91 $class->meta->new_object(@_);
96 my $btree = BinaryTree->new();
97 # ... $btree is an empty hash, no keys are initialized yet
101 This is an example metclass in which all attributes are created
102 lazily. This means that no entries are made in the instance HASH
103 until the last possible moment.
105 The example above of a binary tree is a good use for such a
106 metaclass because it allows the class to be space efficient
107 without complicating the programing of it. This would also be
108 ideal for a class which has a large amount of attributes,
109 several of which are optional.
113 Stevan Little E<lt>stevan@iinteractive.comE<gt>
115 =head1 COPYRIGHT AND LICENSE
117 Copyright 2006 by Infinity Interactive, Inc.
119 L<http://www.iinteractive.com>
121 This library is free software; you can redistribute it and/or modify
122 it under the same terms as Perl itself.