1Moose::Manual::ConstrucUtsieorn(C3o)ntributed Perl DocumMeonotsaet:i:oMnanual::Construction(3)
2
3
4

NAME

6       Moose::Manual::Construction - Object construction (and destruction)
7       with Moose
8

VERSION

10       version 2.2014
11

WHERE'S THE CONSTRUCTOR?

13       Do not define a "new()" method for your classes!
14
15       When you "use Moose" in your class, your class becomes a subclass of
16       Moose::Object. The Moose::Object provides a "new()" method for your
17       class. If you follow our recommendations in
18       Moose::Manual::BestPractices and make your class immutable, then you
19       actually get a class-specific "new()" method "inlined" in your class.
20

OBJECT CONSTRUCTION AND ATTRIBUTES

22       The Moose-provided constructor accepts a hash or hash reference of
23       named parameters matching your attributes (actually, matching their
24       "init_arg"s). This is just another way in which Moose keeps you from
25       worrying how classes are implemented. Simply define a class and you're
26       ready to start creating objects!
27

OBJECT CONSTRUCTION HOOKS

29       Moose lets you hook into object construction. You can validate an
30       object's state, do logging, customize construction from parameters
31       which do not match your attributes, or maybe allow non-hash(ref)
32       constructor arguments. You can do this by creating "BUILD" and/or
33       "BUILDARGS" methods.
34
35       If these methods exist in your class, Moose will arrange for them to be
36       called as part of the object construction process.
37
38   BUILDARGS
39       The "BUILDARGS" method is called as a class method before an object is
40       created. It will receive all of the arguments that were passed to
41       "new()" as-is, and is expected to return a hash reference. This hash
42       reference will be used to construct the object, so it should contain
43       keys matching your attributes' names (well, "init_arg"s).
44
45       One common use for "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,
48       "Person->new($ssn)".
49
50       Without a "BUILDARGS" method, Moose will complain, because it expects a
51       hash or hash reference. We can use the "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 "$class->$orig". This will call the default
67       "BUILDARGS" in Moose::Object. This method takes care of distinguishing
68       between a hash reference and a plain hash for you.
69
70   BUILD
71       The "BUILD" method is called after an object is created. There are
72       several reasons to use a "BUILD" method. One of the most common is to
73       check that the object state is valid. While we can validate individual
74       attributes through the use of types, we can't validate the state of a
75       whole object that way.
76
77         sub BUILD {
78             my $self = shift;
79
80             if ( $self->country_of_residence eq 'USA' ) {
81                 die 'All US residents must have an SSN'
82                     unless $self->has_ssn;
83             }
84         }
85
86       Another use of a "BUILD" method could be for logging or tracking object
87       creation.
88
89         sub BUILD {
90             my $self = shift;
91
92             debug( 'Made a new person - SSN = ', $self->ssn, );
93         }
94
95       The "BUILD" method is called with the hash reference of the parameters
96       passed to the constructor (after munging by "BUILDARGS"). This gives
97       you a chance to do something with parameters that do not represent
98       object attributes.
99
100         sub BUILD {
101             my $self = shift;
102             my $args = shift;
103
104             $self->add_friend(
105                 My::User->new(
106                     user_id => $args->{user_id},
107                 )
108             );
109         }
110
111       BUILD and parent classes
112
113       The interaction between multiple "BUILD" methods in an inheritance
114       hierarchy is different from normal Perl methods. You should never call
115       "$self->SUPER::BUILD", nor should you ever apply a method modifier to
116       "BUILD". Roles are an exception to this rule, though: it's completely
117       acceptable to apply a method modifier to "BUILD" in a role; you can
118       even provide an empty "BUILD" subroutine in a role so the role is
119       applicable even to classes without their own "BUILD".
120
121       Moose arranges to have all of the "BUILD" methods in a hierarchy called
122       when an object is constructed, from parents to children. This might be
123       surprising at first, because it reverses the normal order of method
124       inheritance.
125
126       The theory behind this is that "BUILD" methods can only be used for
127       increasing specialization of a class's constraints, so it makes sense
128       to call the least specific "BUILD" method first. Also, this is how Perl
129       6 does it.
130

OBJECT DESTRUCTION

132       Moose provides a hook for object destruction with the "DEMOLISH"
133       method. As with "BUILD", you should never explicitly call
134       "$self->SUPER::DEMOLISH". Moose will arrange for all of the "DEMOLISH"
135       methods in your hierarchy to be called, from most to least specific.
136
137       Each "DEMOLISH" method is called with a single argument. This is a
138       boolean value indicating whether or not this method was called as part
139       of the global destruction process (when the Perl interpreter exits).
140
141       In most cases, Perl's built-in garbage collection is sufficient, and
142       you won't need to provide a "DEMOLISH" method.
143
144   Error Handling During Destruction
145       The interaction of object destruction and Perl's global $@ and $?
146       variables can be very confusing.
147
148       Moose always localizes $? when an object is being destroyed. This means
149       that if you explicitly call "exit", that exit code will be preserved
150       even if an object's destructor makes a system call.
151
152       Moose also preserves $@ against any "eval" calls that may happen during
153       object destruction. However, if an object's "DEMOLISH" method actually
154       dies, Moose explicitly rethrows that error.
155
156       If you do not like this behavior, you will have to provide your own
157       "DESTROY" method and use that instead of the one provided by
158       Moose::Object. You can do this to preserve $@ and capture any errors
159       from object destruction by creating an error stack.
160

AUTHORS

162       •   Stevan Little <stevan@cpan.org>
163
164       •   Dave Rolsky <autarch@urth.org>
165
166       •   Jesse Luehrs <doy@cpan.org>
167
168       •   Shawn M Moore <sartak@cpan.org>
169
170       •   יובל קוג'מן (Yuval Kogman) <nothingmuch@woobling.org>
171
172       •   Karen Etheridge <ether@cpan.org>
173
174       •   Florian Ragwitz <rafl@debian.org>
175
176       •   Hans Dieter Pearcey <hdp@cpan.org>
177
178       •   Chris Prather <chris@prather.org>
179
180       •   Matt S Trout <mstrout@cpan.org>
181
183       This software is copyright (c) 2006 by Infinity Interactive, Inc.
184
185       This is free software; you can redistribute it and/or modify it under
186       the same terms as the Perl 5 programming language system itself.
187
188
189
190perl v5.32.1                      2021-01-27    Moose::Manual::Construction(3)
Impressum