6 Moose::Cookbook::Basics::Recipe8 - Builder methods and lazy_build
13 has 'node' => (is => 'rw', isa => 'Any');
18 predicate => 'has_parent',
25 predicate => 'has_left',
27 builder => '_build_child_tree',
33 predicate => 'has_right',
35 builder => '_build_child_tree',
38 before 'right', 'left' => sub {
39 my ($self, $tree) = @_;
40 $tree->parent($self) if defined $tree;
43 sub _build_child_tree {
46 return BinaryTree->new( parent => $self );
51 If you've already read L<Moose::Cookbook::Basics::Recipe3>, then this
52 example should look very familiar. In fact, all we've done here is
53 replace the attribute's C<default> parameter with a C<builder>.
55 In this particular case, the C<default> and C<builder> options act in
56 exactly the same way. When the C<left> or C<right> attribute is read,
57 Moose calls the builder method to initialize the attribute.
59 Note that Moose calls the builder method I<on the object which has the
60 attribute>. Here's an example:
62 my $tree = BinaryTree->new();
64 my $left = $tree->left();
66 When C<< $tree->left() >> is called, Moose calls C<<
67 $tree->_build_child_tree() >> in order to populate the C<left>
68 attribute. If we had passed C<left> to the original constructor, the
69 builder would not be called.
71 There are some differences between C<default> and C<builder>. Notably,
72 a builder is subclassable, and can be composed from a role. See
73 L<Moose::Manual::Attributes> for more details.
75 =head2 The lazy_build shortcut
77 The C<lazy_build> attribute option can be used as sugar to specify
78 a whole set of attribute options at once:
86 This is a shorthand for:
93 builder => '_build_animal',
94 predicate => 'has_animal',
95 clearer => 'clear_animal',
98 If your attribute starts with an underscore, Moose is smart and will
99 do the right thing with the C<predicate> and C<clearer>, making them
100 both start with an underscore. The C<builder> method I<always> starts
103 You can read more about C<lazy_build> in L<Moose::Manual::Attributes>
107 The C<builder> option is a more OO-friendly version of the C<default>
108 functionality. It also separates the default-generating code into a
109 well-defined method. Sprinkling your attribute definitions with
110 anonymous subroutines can be quite ugly and hard to follow.
114 Dave Rolsky E<lt>autarch@urth.orgE<gt>
116 =head1 COPYRIGHT AND LICENSE
118 Copyright 2006-2009 by Infinity Interactive, Inc.
120 L<http://www.iinteractive.com>
122 This library is free software; you can redistribute it and/or modify
123 it under the same terms as Perl itself.