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