changelog
[gitmo/Moose.git] / lib / Moose / Manual / Types.pod
1 package Moose::Manual::Types;
2
3 # ABSTRACT: Moose's type system
4
5 __END__
6
7 =pod
8
9 =head1 TYPES IN PERL?
10
11 Moose provides its own type system for attributes. You can also use
12 these types to validate method parameters with the help of a MooseX
13 module.
14
15 Moose's type system is based on a combination of Perl 5's own
16 I<implicit> types and some Perl 6 concepts. You can create your
17 own subtypes with custom constraints, making it easy to express any
18 sort of validation.
19
20 Types have names, and you can re-use them by name, making it easy to
21 share types throughout a large application.
22
23 However, this is not a "real" type system. Moose does not magically make Perl
24 start associating types with variables. This is just an advanced parameter
25 checking system which allows you to associate a name with a constraint.
26
27 That said, it's still pretty damn useful, and we think it's one of the
28 things that makes Moose both fun and powerful. Taking advantage of the
29 type system makes it much easier to ensure that you are getting valid
30 data, and it also contributes greatly to code maintainability.
31
32 =head1 THE TYPES
33
34 The basic Moose type hierarchy looks like this
35
36   Any
37   Item
38       Bool
39       Maybe[`a]
40       Undef
41       Defined
42           Value
43               Str
44                   Num
45                       Int
46                   ClassName
47                   RoleName
48           Ref
49               ScalarRef[`a]
50               ArrayRef[`a]
51               HashRef[`a]
52               CodeRef
53               RegexpRef
54               GlobRef
55                   FileHandle
56               Object
57
58 In practice, the only difference between C<Any> and C<Item> is
59 conceptual. C<Item> is used as the top-level type in the hierarchy.
60
61 The rest of these types correspond to existing Perl concepts.
62 In particular:
63
64 =over 4
65
66 =item
67
68 C<Bool> accepts C<1> for true, and undef, 0, or the empty string as false.
69
70 =item
71
72 C<Maybe[`a]> accepts either C<`a> or C<undef>.
73
74 =item
75
76 C<Num> accepts anything that perl thinks looks like a number (see L<Scalar::Util/looks_like_number>).
77
78 =item
79
80 C<ClassName> and C<RoleName> accept strings that are either the name of a class or the name of a role. The class/role must already be loaded when the constraint is checked.
81
82 =item
83
84 C<FileHandle> accepts either an L<IO::Handle> object or a builtin perl filehandle (see L<Scalar::Util/openhandle>).
85
86 =item
87
88 C<Object> accepts any blessed reference.
89
90 =back
91
92 The types followed by "[`a]" can be parameterized. So instead of just
93 plain C<ArrayRef> we can say that we want C<ArrayRef[Int]> instead. We
94 can even do something like C<HashRef[ArrayRef[Str]]>.
95
96 The C<Maybe[`a]> type deserves a special mention. Used by itself, it
97 doesn't really mean anything (and is equivalent to C<Item>). When it
98 is parameterized, it means that the value is either C<undef> or the
99 parameterized type. So C<Maybe[Int]> means an integer or C<undef>.
100
101 For more details on the type hierarchy, see
102 L<Moose::Util::TypeConstraints>.
103
104 =head1 WHAT IS A TYPE?
105
106 It's important to realize that types are not classes (or
107 packages). Types are just objects (L<Moose::Meta::TypeConstraint>
108 objects, to be exact) with a name and a constraint. Moose maintains a
109 global type registry that lets it convert names like C<Num> into the
110 appropriate object.
111
112 However, class names I<can be> type names. When you define a new class
113 using Moose, it defines an associated type name behind the scenes:
114
115   package MyApp::User;
116
117   use Moose;
118
119 Now you can use C<'MyApp::User'> as a type name:
120
121   has creator => (
122       is  => 'ro',
123       isa => 'MyApp::User',
124   );
125
126 However, for non-Moose classes there's no magic. You may have to
127 explicitly declare the class type. This is a bit muddled because Moose
128 assumes that any unknown type name passed as the C<isa> value for an
129 attribute is a class. So this works:
130
131   has 'birth_date' => (
132       is  => 'ro',
133       isa => 'DateTime',
134   );
135
136 In general, when Moose is presented with an unknown name, it assumes
137 that the name is a class:
138
139   subtype 'ModernDateTime'
140       => as 'DateTime'
141       => where { $_->year() >= 1980 }
142       => message { 'The date you provided is not modern enough' };
143
144   has 'valid_dates' => (
145       is  => 'ro',
146       isa => 'ArrayRef[DateTime]',
147   );
148
149 Moose will assume that C<DateTime> is a class name in both of these
150 instances.
151
152 =head1 SUBTYPES
153
154 Moose uses subtypes in its built-in hierarchy. For example, C<Int> is
155 a child of C<Num>.
156
157 A subtype is defined in terms of a parent type and a constraint. Any
158 constraints defined by the parent(s) will be checked first, followed by
159 constraints defined by the subtype. A value must pass I<all> of these
160 checks to be valid for the subtype.
161
162 Typically, a subtype takes the parent's constraint and makes it more
163 specific.
164
165 A subtype can also define its own constraint failure message. This
166 lets you do things like have an error "The value you provided (20),
167 was not a valid rating, which must be a number from 1-10." This is
168 much friendlier than the default error, which just says that the value
169 failed a validation check for the type.
170
171 Here's a simple (and useful) subtype example:
172
173   subtype 'PositiveInt'
174       => as 'Int'
175       => where { $_ > 0 }
176       => message { "The number you provided, $_, was not a positive number" }
177
178 Note that the sugar functions for working with types are all exported
179 by L<Moose::Util::TypeConstraints>.
180
181 =head1 TYPE NAMES
182
183 Type names are global throughout the current Perl
184 interpreter. Internally, Moose maps names to type objects via a
185 L<registry|Moose::Meta::TypeConstraint::Registry>.
186
187 If you have multiple apps or libraries all using Moose in the same
188 process, you could have problems with collisions. We recommend that
189 you prefix names with some sort of namespace indicator to prevent
190 these sorts of collisions.
191
192 For example, instead of calling a type "PositiveInt", call it
193 "MyApp::Type::PositiveInt" or "MyApp::Types::PositiveInt". We
194 recommend that you centralize all of these definitions in a single
195 package, C<MyApp::Types>, which can be loaded by other classes in your
196 application.
197
198 However, before you do this, you should look at the L<MooseX::Types>
199 module. This module makes it easy to create a "type library" module, which can
200 export your types as perl constants.
201
202   has 'counter' => (is => 'rw', isa => PositiveInt);
203
204 This lets you use a short name rather than needing to fully qualify the name
205 everywhere. It also allows you to write easily create parameterized types:
206
207   has 'counts' => (is => 'ro', isa => HashRef[PositiveInt]);
208
209 This module will check your names at compile time, and is generally more
210 robust than the string type parsing for complex cases.
211
212 =head1 COERCION
213
214 A coercion lets you tell Moose to automatically convert one type to another.
215
216   subtype 'ArrayRefOfInts'
217       => as 'ArrayRef[Int]';
218
219   coerce 'ArrayRefOfInts'
220       => from 'Int'
221       => via { [ $_ ] };
222
223 You'll note that we created a subtype rather than coercing C<ArrayRef[Int]>
224 directly. It's a bad idea to add coercions to the raw built in
225 types.
226
227 Coercions are global, just like type names, so a coercion applied to a built
228 in type is seen by all modules using Moose types. This is I<another> reason
229 why it is good to namespace your types.
230
231 Moose will I<never> try to coerce a value unless you explicitly ask for
232 it. This is done by setting the C<coerce> attribute option to a true value:
233
234   package Foo;
235
236   has 'sizes' => (
237       is     => 'ro',
238       isa    => 'ArrayRefOfInts',
239       coerce => 1,
240   );
241
242   Foo->new( sizes => 42 );
243
244 This code example will do the right thing, and the newly created
245 object will have C<[ 42 ]> as its C<sizes> attribute.
246
247 =head2 Deep coercion
248
249 Deep coercion is the coercion of type parameters for parameterized
250 types. Let's take these types as an example:
251
252   subtype 'HexNum'
253       => as 'Str'
254       => where { /[a-f0-9]/i };
255
256   coerce 'Int'
257       => from 'HexNum'
258       => via { hex $_ };
259
260   has 'sizes' => (
261       is     => 'ro',
262       isa    => 'ArrayRef[Int]',
263       coerce => 1,
264   );
265
266 If we try passing an array reference of hex numbers for the C<sizes>
267 attribute, Moose will not do any coercion.
268
269 However, you can define a set of subtypes to enable coercion between
270 two parameterized types.
271
272   subtype 'ArrayRefOfHexNums'
273       => as 'ArrayRef[HexNum]';
274
275   subtype 'ArrayRefOfInts'
276       => as 'ArrayRef[Int]';
277
278   coerce 'ArrayRefOfInts'
279       => from 'ArrayRefOfHexNums'
280       => via { [ map { hex } @{$_} ] };
281
282   Foo->new( sizes => [ 'a1', 'ff', '22' ] );
283
284 Now Moose will coerce the hex numbers to integers.
285
286 Moose does not attempt to chain coercions, so it will not
287 coerce a single hex number. To do that, we need to define a separate
288 coercion:
289
290   coerce 'ArrayRefOfInts'
291       => from 'HexNum'
292       => via { [ hex $_ ] };
293
294 Yes, this can all get verbose, but coercion is tricky magic, and we
295 think it's best to make it explicit.
296
297 =head1 TYPE UNIONS
298
299 Moose allows you to say that an attribute can be of two or more
300 disparate types. For example, we might allow an C<Object> or
301 C<FileHandle>:
302
303   has 'output' => (
304       is  => 'rw',
305       isa => 'Object | FileHandle',
306   );
307
308 Moose actually parses that string and recognizes that you are creating
309 a type union. The C<output> attribute will accept any sort of object,
310 as well as an unblessed file handle. It is up to you to do the right
311 thing for each of them in your code.
312
313 Whenever you use a type union, you should consider whether or not
314 coercion might be a better answer.
315
316 For our example above, we might want to be more specific, and insist
317 that output be an object with a C<print> method:
318
319   subtype 'CanPrint'
320       => as 'Object'
321       => where { $_->can('print') };
322
323 We can coerce file handles to an object that satisfies this condition
324 with a simple wrapper class:
325
326   package FHWrapper;
327
328   use Moose;
329
330   has 'handle' => (
331       is  => 'rw',
332       isa => 'FileHandle',
333   );
334
335   sub print {
336       my $self = shift;
337       my $fh   = $self->handle();
338
339       print {$fh} @_;
340   }
341
342 Now we can define a coercion from C<FileHandle> to our wrapper class:
343
344   coerce 'CanPrint'
345       => from 'FileHandle'
346       => via { FHWrapper->new( handle => $_ ) };
347
348   has 'output' => (
349       is     => 'rw',
350       isa    => 'CanPrint',
351       coerce => 1,
352   );
353
354 This pattern of using a coercion instead of a type union will help
355 make your class internals simpler.
356
357 =head1 TYPE CREATION HELPERS
358
359 The L<Moose::Util::TypeConstraints> module exports a number of helper
360 functions for creating specific kinds of types. These include
361 C<class_type>, C<role_type>, and C<maybe_type>. See the docs for
362 details.
363
364 One helper worth noting is C<enum>, which allows you to create a
365 subtype of C<Str> that only allows the specified values:
366
367   enum 'RGB' => qw( red green blue );
368
369 This creates a type named C<RGB>.
370
371 =head1 ANONYMOUS TYPES
372
373 All of the type creation functions return a type object. This type
374 object can be used wherever you would use a type name, as a parent
375 type, or as the value for an attribute's C<isa> option:
376
377   has 'size' => (
378       is  => 'ro',
379       isa => subtype( 'Int' => where { $_ > 0 } ),
380   );
381
382 This is handy when you want to create a one-off type and don't want to
383 "pollute" the global namespace registry.
384
385 =head1 VALIDATING METHOD PARAMETERS
386
387 Moose does not provide any means of validating method
388 parameters. However, there are several MooseX extensions on CPAN which
389 let you do this.
390
391 The simplest and least sugary is L<MooseX::Params::Validate>. This
392 lets you validate a set of named parameters using Moose types:
393
394   use Moose;
395   use MooseX::Params::Validate;
396
397   sub foo {
398       my $self   = shift;
399       my %params = validated_hash(
400           \@_,
401           bar => { isa => 'Str', default => 'Moose' },
402       );
403       ...
404   }
405
406 L<MooseX::Params::Validate> also supports coercions.
407
408 There are several more powerful extensions that support method
409 parameter validation using Moose types, including
410 L<MooseX::Method::Signatures>, which gives you a full-blown C<method>
411 keyword.
412
413   method morning ( Str $name ) {
414       $self->say("Good morning ${name}!");
415   }
416
417 =head1 LOAD ORDER ISSUES
418
419 Because Moose types are defined at runtime, you may run into load
420 order problems. In particular, you may want to use a class's type
421 constraint before that type has been defined.
422
423 In order to ameliorate this problem, we recommend defining I<all> of your
424 custom types in one module, C<MyApp::Types>, and then loading this module in
425 all of your other modules.
426
427 =cut