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