24689c06bf346f3a6f29988ddb90308b515b3499
[gitmo/Moose.git] / lib / Moose / Manual / Construction.pod
1 =pod
2
3 =head1 NAME
4
5 Moose::Manual::Construction - Object construction (and destruction) with Moose
6
7 =head1 WHERE'S THE CONSTRUCTOR?
8
9 B<Do not define a C<new()> method for your classes!>
10
11 When you C<use Moose> in your class, your class becomes a subclass of
12 L<Moose::Object>. The L<Moose::Object> provides a C<new()> method for your
13 class. If you follow our recommendations in L<Moose::Manual::BestPractices>
14 and make your class immutable, then you actually get a class-specific C<new()>
15 method "inlined" in your class.
16
17 =head1 OBJECT CONSTRUCTION AND ATTRIBUTES
18
19 The Moose-provided constructor accepts a hash or hash reference of
20 named parameters matching your attributes (actually, matching their
21 C<init_arg>s). This is just another way in which Moose keeps you from
22 worrying I<how> classes are implemented. Simply define a class and
23 you're ready to start creating objects!
24
25 =head1 OBJECT CONSTRUCTION HOOKS
26
27 Moose lets you hook into object construction. You can validate an
28 object's state, do logging, customize construction from parameters which
29 do not match your attributes, or maybe allow non-hash(ref) constructor
30 arguments. You can do this by creating C<BUILD> and/or C<BUILDARGS>
31 methods.
32
33 If these methods exist in your class, Moose will arrange for them to
34 be called as part of the object construction process.
35
36 =head2 BUILDARGS
37
38 The C<BUILDARGS> method is called as a class method I<before> an
39 object is created. It will receive all of the arguments that were
40 passed to C<new()> I<as-is>, and is expected to return a hash
41 reference. This hash reference will be used to construct the object,
42 so it should contain keys matching your attributes' names (well,
43 C<init_arg>s).
44
45 One common use for C<BUILDARGS> is to accommodate a non-hash(ref)
46 calling style. For example, we might want to allow our Person class to
47 be called with a single argument of a social security number, C<<
48 Person->new($ssn) >>.
49
50 Without a C<BUILDARGS> method, Moose will complain, because it expects
51 a hash or hash reference. We can use the C<BUILDARGS> method to
52 accommodate this calling style:
53
54   around BUILDARGS => sub {
55       my $orig  = shift;
56       my $class = shift;
57
58       if ( @_ == 1 && !ref $_[0] ) {
59           return $class->$orig( ssn => $_[0] );
60       }
61       else {
62           return $class->$orig(@_);
63       }
64   };
65
66 Note the call to C<< $class->$orig >>. This will call the default C<BUILDARGS>
67 in L<Moose::Object>. This method takes care of distinguishing between a hash
68 reference and a plain hash for you.
69
70 =head2 BUILD
71
72 The C<BUILD> method is called I<after> an object is created. There are
73 several reasons to use a C<BUILD> method. One of the most common is to
74 check that the object state is valid. While we can validate individual
75 attributes through the use of types, we can't validate the state of a
76 whole object that way.
77
78   sub BUILD {
79       my $self = shift;
80
81       if ( $self->country_of_residence eq 'USA' ) {
82           die 'All US residents must have an SSN'
83               unless $self->has_ssn;
84       }
85   }
86
87 Another use of a C<BUILD> method could be for logging or tracking
88 object creation.
89
90   sub BUILD {
91       my $self = shift;
92
93       debug( 'Made a new person - SSN = ', $self->ssn, );
94   }
95
96
97 The C<BUILD> method is called with the hash reference of the parameters passed
98 to the constructor (after munging by C<BUILDARGS>). This gives you a chance to
99 do something with parameters that do not represent object attributes.
100
101   sub BUILD {
102       my $self = shift;
103       my $args = shift;
104
105       $self->add_friend(
106           My::User->new(
107               user_id => $args->{user_id},
108           )
109       );
110   }
111
112 =head3 BUILD and parent classes
113
114 The interaction between multiple C<BUILD> methods in an inheritance hierarchy
115 is different from normal Perl methods. B<You should never call C<<
116 $self->SUPER::BUILD >>>, nor should you ever apply a method modifier to
117 C<BUILD>.
118
119 Moose arranges to have all of the C<BUILD> methods in a hierarchy
120 called when an object is constructed, I<from parents to
121 children>. This might be surprising at first, because it reverses the
122 normal order of method inheritance.
123
124 The theory behind this is that C<BUILD> methods can only be used for
125 increasing specialization of a class's constraints, so it makes sense
126 to call the least specific C<BUILD> method first. Also, this is how
127 Perl 6 does it.
128
129 =head1 OBJECT DESTRUCTION
130
131 Moose provides a hook for object destruction with the C<DEMOLISH>
132 method. As with C<BUILD>, you should never explicitly call C<<
133 $self->SUPER::DEMOLISH >>. Moose will arrange for all of the
134 C<DEMOLISH> methods in your hierarchy to be called, from most to least
135 specific.
136
137 Each C<DEMOLISH> method is called with a single argument.
138
139 In most cases, Perl's built-in garbage collection is sufficient, and
140 you won't need to provide a C<DEMOLISH> method.
141
142 =head2 Error Handling During Destruction
143
144 The interaction of object destruction and Perl's global C<$@> and C<$?>
145 variables can be very confusing.
146
147 Moose always localizes C<$?> when an object is being destroyed. This means
148 that if you explicitly call C<exit>, that exit code will be preserved even if
149 an object's destructor makes a system call.
150
151 Moose also preserves C<$@> against any C<eval> calls that may happen during
152 object destruction. However, if an object's C<DEMOLISH> method actually dies,
153 Moose explicitly rethrows that error.
154
155 If you do not like this behavior, you will have to provide your own C<DESTROY>
156 method and use that instead of the one provided by L<Moose::Object>. You can
157 do this to preserve C<$@> I<and> capture any errors from object destruction by
158 creating an error stack.
159
160 =head1 AUTHOR
161
162 Dave Rolsky E<lt>autarch@urth.orgE<gt>
163
164 =head1 COPYRIGHT AND LICENSE
165
166 Copyright 2009 by Infinity Interactive, Inc.
167
168 L<http://www.iinteractive.com>
169
170 This library is free software; you can redistribute it and/or modify
171 it under the same terms as Perl itself.
172
173 =cut