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