2 package # hide the package from PAUSE
10 use base 'Class::MOP::Class';
12 sub construct_instance {
13 my ($class, %params) = @_;
15 foreach my $attr (map { $_->{attribute} } $class->compute_all_applicable_attributes()) {
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 = $attr->has_init_arg() ? $attr->init_arg() : $attr->name;
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 $instance->{$attr->name} = $val if defined $val;
29 package # hide the package from PAUSE
35 our $VERSION = '0.02';
37 use base 'Class::MOP::Attribute';
39 sub generate_accessor_method {
40 my ($self, $attr_name) = @_;
42 if (scalar(@_) == 2) {
43 $_[0]->{$attr_name} = $_[1];
46 if (!exists $_[0]->{$attr_name}) {
47 my $attr = $self->associated_class->get_attribute($attr_name);
48 $_[0]->{$attr_name} = $attr->has_default ? $attr->default($_[0]) : undef;
55 sub generate_reader_method {
56 my ($self, $attr_name) = @_;
58 if (!exists $_[0]->{$attr_name}) {
59 my $attr = $self->associated_class->get_attribute($attr_name);
60 $_[0]->{$attr_name} = $attr->has_default ? $attr->default($_[0]) : undef;
74 LazyClass - An example metaclass with lazy initialization
81 LazyClass->initialize($_[0] => (
82 ':attribute_metaclass' => 'LazyClass::Attribute'
86 BinaryTree->meta->add_attribute('$:node' => (
91 BinaryTree->meta->add_attribute('$:left' => (
93 default => sub { BinaryTree->new() }
96 BinaryTree->meta->add_attribute('$:right' => (
98 default => sub { BinaryTree->new() }
103 bless $class->meta->construct_instance(@_) => $class;
108 my $btree = BinaryTree->new();
109 # ... $btree is an empty hash, no keys are initialized yet
113 This is an example metclass in which all attributes are created
114 lazily. This means that no entries are made in the instance HASH
115 until the last possible moment.
117 The example above of a binary tree is a good use for such a
118 metaclass because it allows the class to be space efficient
119 without complicating the programing of it. This would also be
120 ideal for a class which has a large amount of attributes,
121 several of which are optional.
125 Stevan Little E<lt>stevan@iinteractive.comE<gt>
127 =head1 COPYRIGHT AND LICENSE
129 Copyright 2006 by Infinity Interactive, Inc.
131 L<http://www.iinteractive.com>
133 This library is free software; you can redistribute it and/or modify
134 it under the same terms as Perl itself.