1Moose::Manual::FAQ(3) User Contributed Perl DocumentationMoose::Manual::FAQ(3)
2
3
4

NAME

6       Moose::Manual::FAQ - Frequently asked questions about Moose
7

VERSION

9       version 2.2013
10

FREQUENTLY ASKED QUESTIONS

12   Module Stability
13       Is Moose "production ready"?
14
15       Yes! Many sites with household names are using Moose to build high-
16       traffic services. Countless others are using Moose in production.  See
17       <http://moose.iinteractive.com/about.html#organizations> for a partial
18       list.
19
20       As of this writing, Moose is a dependency of several hundred CPAN
21       modules. <https://metacpan.org/requires/module/Moose>
22
23       Is Moose's API stable?
24
25       Yes. The sugary API, the one 95% of users will interact with, is very
26       stable. Any changes will be 100% backwards compatible.
27
28       The meta API is less set in stone. We reserve the right to tweak parts
29       of it to improve efficiency or consistency. This will not be done
30       lightly. We do perform deprecation cycles. We really do not like making
31       ourselves look bad by breaking your code.  Submitting test cases is the
32       best way to ensure that your code is not inadvertently broken by
33       refactoring.
34
35       I heard Moose is slow, is this true?
36
37       Again, this one is tricky, so Yes and No.
38
39       Firstly, nothing in life is free, and some Moose features do cost more
40       than others. It is also the policy of Moose to only charge you for the
41       features you use, and to do our absolute best to not place any extra
42       burdens on the execution of your code for features you are not using.
43       Of course using Moose itself does involve some overhead, but it is
44       mostly compile time. At this point we do have some options available
45       for getting the speed you need.
46
47       Currently we provide the option of making your classes immutable as a
48       means of boosting speed. This will mean a slightly larger compile time
49       cost, but the runtime speed increase (especially in object
50       construction) is pretty significant. This can be done with the
51       following code:
52
53         MyClass->meta->make_immutable();
54
55   Constructors
56       How do I write custom constructors with Moose?
57
58       Ideally, you should never write your own "new" method, and should use
59       Moose's other features to handle your specific object construction
60       needs. Here are a few scenarios, and the Moose way to solve them;
61
62       If you need to call initialization code post instance construction,
63       then use the "BUILD" method. This feature is taken directly from Perl
64       6. Every "BUILD" method in your inheritance chain is called (in the
65       correct order) immediately after the instance is constructed.  This
66       allows you to ensure that all your superclasses are initialized
67       properly as well. This is the best approach to take (when possible)
68       because it makes subclassing your class much easier.
69
70       If you need to affect the constructor's parameters prior to the
71       instance actually being constructed, you have a number of options.
72
73       To change the parameter processing as a whole, you can use the
74       "BUILDARGS" method. The default implementation accepts key/value pairs
75       or a hash reference. You can override it to take positional args, or
76       any other format
77
78       To change the handling of individual parameters, there are coercions
79       (See the Moose::Cookbook::Basics::HTTP_SubtypesAndCoercion for a
80       complete example and explanation of coercions). With coercions it is
81       possible to morph argument values into the correct expected types. This
82       approach is the most flexible and robust, but does have a slightly
83       higher learning curve.
84
85       How do I make non-Moose constructors work with Moose?
86
87       Usually the correct approach to subclassing a non-Moose class is
88       delegation.  Moose makes this easy using the "handles" keyword,
89       coercions, and "lazy_build", so subclassing is often not the ideal
90       route.
91
92       That said, if you really need to inherit from a non-Moose class, see
93       Moose::Cookbook::Basics::DateTime_ExtendingNonMooseParent for an
94       example of how to do it, or take a look at "MooseX::NonMoose" in
95       Moose::Manual::MooseX.
96
97   Accessors
98       How do I tell Moose to use get/set accessors?
99
100       The easiest way to accomplish this is to use the "reader" and "writer"
101       attribute options:
102
103         has 'bar' => (
104             isa    => 'Baz',
105             reader => 'get_bar',
106             writer => 'set_bar',
107         );
108
109       Moose will still take advantage of type constraints, triggers, etc.
110       when creating these methods.
111
112       If you do not like this much typing, and wish it to be a default for
113       your classes, please see MooseX::FollowPBP. This extension will allow
114       you to write:
115
116         has 'bar' => (
117             isa => 'Baz',
118             is  => 'rw',
119         );
120
121       Moose will create separate "get_bar" and "set_bar" methods instead of a
122       single "bar" method.
123
124       If you like "bar" and "set_bar", see MooseX::SemiAffordanceAccessor.
125
126       NOTE: This cannot be set globally in Moose, as that would break other
127       classes which are built with Moose. You can still save on typing by
128       defining a new "MyApp::Moose" that exports Moose's sugar and then turns
129       on MooseX::FollowPBP. See
130       Moose::Cookbook::Extending::Mooseish_MooseSugar.
131
132       How can I inflate/deflate values in accessors?
133
134       Well, the first question to ask is if you actually need both inflate
135       and deflate.
136
137       If you only need to inflate, then we suggest using coercions. Here is
138       some basic sample code for inflating a DateTime object:
139
140         class_type 'DateTime';
141
142         coerce 'DateTime'
143             => from 'Str'
144             => via { DateTime::Format::MySQL->parse_datetime($_) };
145
146         has 'timestamp' => (is => 'rw', isa => 'DateTime', coerce => 1);
147
148       This creates a custom type for DateTime objects, then attaches a
149       coercion to that type. The "timestamp" attribute is then told to expect
150       a "DateTime" type, and to try to coerce it. When a "Str" type is given
151       to the "timestamp" accessor, it will attempt to coerce the value into a
152       "DateTime" object using the code in found in the "via" block.
153
154       For a more comprehensive example of using coercions, see the
155       Moose::Cookbook::Basics::HTTP_SubtypesAndCoercion.
156
157       If you need to deflate your attribute's value, the current best
158       practice is to add an "around" modifier to your accessor:
159
160         # a timestamp which stores as
161         # seconds from the epoch
162         has 'timestamp' => (is => 'rw', isa => 'Int');
163
164         around 'timestamp' => sub {
165             my $next = shift;
166             my $self = shift;
167
168             return $self->$next unless @_;
169
170             # assume we get a DateTime object ...
171             my $timestamp = shift;
172             return $self->$next( $timestamp->epoch );
173         };
174
175       It is also possible to do deflation using coercion, but this tends to
176       get quite complex and require many subtypes. An example of this is
177       outside the scope of this document, ask on #moose or send a mail to the
178       list.
179
180       Still another option is to write a custom attribute metaclass, which is
181       also outside the scope of this document, but we would be happy to
182       explain it on #moose or the mailing list.
183
184   Method Modifiers
185       How can I affect the values in @_ using "before"?
186
187       You can't, actually: "before" only runs before the main method, and it
188       cannot easily affect the method's execution.
189
190       You similarly can't use "after" to affect the return value of a method.
191
192       We limit "before" and "after" because this lets you write more concise
193       code. You do not have to worry about passing @_ to the original method,
194       or forwarding its return value (being careful to preserve context).
195
196       The "around" method modifier has neither of these limitations, but is a
197       little more verbose.
198
199       Alternatively, the MooseX::Mangle extension provides the "mangle_args"
200       function, which does allow you to affect @_.
201
202       Can I use "before" to stop execution of a method?
203
204       Yes, but only if you throw an exception. If this is too drastic a
205       measure then we suggest using "around" instead. The "around" method
206       modifier is the only modifier which can gracefully prevent execution of
207       the main method. Here is an example:
208
209           around 'baz' => sub {
210               my $next = shift;
211               my ($self, %options) = @_;
212               unless ($options->{bar} eq 'foo') {
213                   return 'bar';
214               }
215               $self->$next(%options);
216           };
217
218       By choosing not to call the $next method, you can stop the execution of
219       the main method.
220
221       Alternatively, the MooseX::Mangle extension provides the "guard"
222       function, which will conditionally prevent execution of the original
223       method.
224
225       Why can't I see return values in an "after" modifier?
226
227       As with the "before" modifier, the "after" modifier is simply called
228       after the main method. It is passed the original contents of @_ and not
229       the return values of the main method.
230
231       Again, the arguments are too lengthy as to why this has to be. And as
232       with "before" I recommend using an "around" modifier instead.  Here is
233       some sample code:
234
235         around 'foo' => sub {
236             my $next = shift;
237             my ($self, @args) = @_;
238             my @rv = $next->($self, @args);
239             # do something silly with the return values
240             return reverse @rv;
241         };
242
243       Alternatively, the MooseX::Mangle extension provides the
244       "mangle_return" function, which allows modifying the return values of
245       the original method.
246
247   Type Constraints
248       How can I provide a custom error message for a type constraint?
249
250       Use the "message" option when building the subtype:
251
252         subtype 'NaturalLessThanTen'
253             => as 'Natural'
254             => where { $_ < 10 }
255             => message { "This number ($_) is not less than ten!" };
256
257       This "message" block will be called when a value fails to pass the
258       "NaturalLessThanTen" constraint check.
259
260       Can I turn off type constraint checking?
261
262       There's no support for it in the core of Moose yet. This option may
263       come in a future release.
264
265       Meanwhile there's a MooseX extension that allows you to do this on a
266       per-attribute basis, and if it doesn't do what you it's easy to write
267       one that fits your use case.
268
269       My coercions stopped working with recent Moose, why did you break it?
270
271       Moose 0.76 fixed a case where coercions were being applied even if the
272       original constraint passed. This has caused some edge cases to fail
273       where people were doing something like
274
275           subtype 'Address', as 'Str';
276           coerce 'Address', from 'Str', via { get_address($_) };
277
278       This is not what they intended, because the type constraint "Address"
279       is too loose in this case. It is saying that all strings are Addresses,
280       which is obviously not the case. The solution is to provide a "where"
281       clause that properly restricts the type constraint:
282
283           subtype 'Address', as 'Str', where { looks_like_address($_) };
284
285       This will allow the coercion to apply only to strings that fail to look
286       like an Address.
287
288   Roles
289       Why is BUILD not called for my composed roles?
290
291       "BUILD" is never called in composed roles. The primary reason is that
292       roles are not order sensitive. Roles are composed in such a way that
293       the order of composition does not matter (for information on the deeper
294       theory of this read the original traits papers here
295       <http://www.iam.unibe.ch/~scg/Research/Traits/>).
296
297       Because roles are essentially unordered, it would be impossible to
298       determine the order in which to execute the "BUILD" methods.
299
300       As for alternate solutions, there are a couple.
301
302       ·   Using a combination of lazy and default in your attributes to defer
303           initialization (see the Binary Tree example in the cookbook for a
304           good example of lazy/default usage
305           Moose::Cookbook::Basics::BinaryTree_AttributeFeatures)
306
307       ·   Use attribute triggers, which fire after an attribute is set, to
308           facilitate initialization. These are described in the Moose docs,
309           and examples can be found in the test suite.
310
311       In general, roles should not require initialization; they should either
312       provide sane defaults or should be documented as needing specific
313       initialization. One such way to "document" this is to have a separate
314       attribute initializer which is required for the role. Here is an
315       example of how to do this:
316
317         package My::Role;
318         use Moose::Role;
319
320         has 'height' => (
321             is      => 'rw',
322             isa     => 'Int',
323             lazy    => 1,
324             default => sub {
325                 my $self = shift;
326                 $self->init_height;
327             }
328         );
329
330         requires 'init_height';
331
332       In this example, the role will not compose successfully unless the
333       class provides a "init_height" method.
334
335       If none of those solutions work, then it is possible that a role is not
336       the best tool for the job, and you really should be using classes. Or,
337       at the very least, you should reduce the amount of functionality in
338       your role so that it does not require initialization.
339
340       What are traits, and how are they different from roles?
341
342       In Moose, a trait is almost exactly the same thing as a role, except
343       that traits typically register themselves, which allows you to refer to
344       them by a short name ("Big" vs "MyApp::Role::Big").
345
346       In Moose-speak, a Role is usually composed into a class at compile
347       time, whereas a Trait is usually composed into an instance of a class
348       at runtime to add or modify the behavior of just that instance.
349
350       Outside the context of Moose, traits and roles generally mean exactly
351       the same thing. The original paper called them traits, but Perl 6 will
352       call them roles.
353
354       Can an attribute-generated method (e.g. an accessor) satisfy requires?
355
356       Yes, just be sure to consume the role after declaring your attribute.
357       "Required Attributes" in Moose::Manual::Roles provides an example:
358
359         package Breakable;
360         use Moose::Role;
361         requires 'stress';
362
363         package Car;
364         use Moose;
365         has 'stress' => ( is  => 'rw', isa => 'Int' );
366         with 'Breakable';
367
368       If you mistakenly consume the "Breakable" role before declaring your
369       "stress" attribute, you would see an error like this:
370
371         'Breakable' requires the method 'stress' to be implemented by 'Car' at...
372
373   Moose and Subroutine Attributes
374       Why don't subroutine attributes I inherited from a superclass work?
375
376       Currently when subclassing a module is done at runtime with the
377       "extends" keyword, but attributes are checked at compile time by Perl.
378       To make attributes work, you must place "extends" in a "BEGIN" block so
379       that the attribute handlers will be available at compile time, like
380       this:
381
382         BEGIN { extends qw/Foo/ }
383
384       Note that we're talking about Perl's subroutine attributes here, not
385       Moose attributes:
386
387         sub foo : Bar(27) { ... }
388

AUTHORS

390       ·   Stevan Little <stevan.little@iinteractive.com>
391
392       ·   Dave Rolsky <autarch@urth.org>
393
394       ·   Jesse Luehrs <doy@tozt.net>
395
396       ·   Shawn M Moore <code@sartak.org>
397
398       ·   יובל קוג'מן (Yuval Kogman) <nothingmuch@woobling.org>
399
400       ·   Karen Etheridge <ether@cpan.org>
401
402       ·   Florian Ragwitz <rafl@debian.org>
403
404       ·   Hans Dieter Pearcey <hdp@weftsoar.net>
405
406       ·   Chris Prather <chris@prather.org>
407
408       ·   Matt S Trout <mst@shadowcat.co.uk>
409
411       This software is copyright (c) 2006 by Infinity Interactive, Inc.
412
413       This is free software; you can redistribute it and/or modify it under
414       the same terms as the Perl 5 programming language system itself.
415
416
417
418perl v5.32.0                      2020-07-28             Moose::Manual::FAQ(3)
Impressum