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

FREQUENTLY ASKED QUESTIONS

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

AUTHOR

375       Stevan Little <stevan@iinteractive.com>
376
378       Copyright 2006-2010 by Infinity Interactive, Inc.
379
380       <http://www.iinteractive.com>
381
382       This library is free software; you can redistribute it and/or modify it
383       under the same terms as Perl itself.
384
385
386
387perl v5.12.2                      2010-08-21             Moose::Manual::FAQ(3)
Impressum