2 package # hide the package from PAUSE
10 our $VERSION = '0.01';
12 use base 'Class::MOP::Class';
14 sub construct_instance {
15 my ($class, %params) = @_;
17 foreach my $attr (map { $_->{attribute} } $class->compute_all_applicable_attributes()) {
18 # if the attr has an init_arg, use that, otherwise,
19 # use the attributes name itself as the init_arg
20 my $init_arg = $attr->has_init_arg() ? $attr->init_arg() : $attr->name;
21 # try to fetch the init arg from the %params ...
23 $val = $params{$init_arg} if exists $params{$init_arg};
24 # now add this to the instance structure
25 # only if we have found a value at all
26 $instance->{$attr->name} = $val if defined $val;
31 package # hide the package from PAUSE
37 use Class::MOP 'meta';
39 our $VERSION = '0.01';
41 use base 'Class::MOP::Attribute';
43 sub generate_accessor_method {
44 my ($self, $attr_name) = @_;
46 if (scalar(@_) == 2) {
47 $_[0]->{$attr_name} = $_[1];
50 if (!exists $_[0]->{$attr_name}) {
51 my $attr = $self->associated_class->get_attribute($attr_name);
52 $_[0]->{$attr_name} = $attr->has_default ? $attr->default($_[0]) : undef;
59 sub generate_reader_method {
60 my ($self, $attr_name) = @_;
62 if (!exists $_[0]->{$attr_name}) {
63 my $attr = $self->associated_class->get_attribute($attr_name);
64 $_[0]->{$attr_name} = $attr->has_default ? $attr->default($_[0]) : undef;
78 LazyClass - An example metaclass with lazy initialization
85 LazyClass->initialize($_[0] => (
86 ':attribute_metaclass' => 'LazyClass::Attribute'
90 BinaryTree->meta->add_attribute('$:node' => (
95 BinaryTree->meta->add_attribute('$:left' => (
97 default => sub { BinaryTree->new() }
100 BinaryTree->meta->add_attribute('$:right' => (
102 default => sub { BinaryTree->new() }
107 bless $class->meta->construct_instance(@_) => $class;
112 my $btree = BinaryTree->new();
113 # ... $btree is an empty hash, no keys are initialized yet
117 This is an example metclass in which all attributes are created
118 lazily. This means that no entries are made in the instance HASH
119 until the last possible moment.
121 The example above of a binary tree is a good use for such a
122 metaclass because it allows the class to be space efficient
123 without complicating the programing of it. This would also be
124 ideal for a class which has a large amount of attributes,
125 several of which are optional.
129 Stevan Little E<lt>stevan@iinteractive.comE<gt>
131 =head1 COPYRIGHT AND LICENSE
133 Copyright 2006 by Infinity Interactive, Inc.
135 L<http://www.iinteractive.com>
137 This library is free software; you can redistribute it and/or modify
138 it under the same terms as Perl itself.