5 Moose::Manual::Types - Moose's type system
9 Moose provides its own type system for attributes. You can also use
10 these types to validate method parameters with the help of a MooseX
13 Moose's type system is based on a combination of Perl 5's own
14 I<implicit> types and some Perl 6 concepts. You can easily create your
15 own subtypes with custom constraints, making it easy to express any
18 Types have names, and you can re-use them by name, making it easy to
19 share types throughout a large application.
21 Let us be clear that is not a "real" type system. Moose does not
22 magically make Perl start associating types with variables. This is
23 just an advanced parameter checking system which allows you to
24 associate a name with a constraint.
26 That said, it's still pretty damn useful, and we think it's one of the
27 things that makes Moose both fun and powerful. Taking advantage of the
28 type system makes it much easier to ensure that you are getting valid
29 data, and it also contributes greatly to code maintainability.
33 The basic Moose type hierarchy looks like this
57 In practice, the only difference between C<Any> and C<Item> is
58 conceptual. C<Item> is used as the top-level type in the hierarchy.
60 The rest of these types correspond to existing Perl concepts. For
61 example, a C<Num> is anything that Perl thinks looks like a number, an
62 C<Object> is a blessed reference, etc.
64 The types followed by "[`a]" can be parameterized. So instead of just
65 plain C<ArrayRef> we can say that we want C<ArrayRef[Int]> instead. We
66 can even do something like C<HashRef[ArrayRef[Str]]>.
68 The C<Maybe[`a]> type deserves a special mention. Used by itself, it
69 doesn't really mean anything (and is equivalent to C<Item>). When it
70 is parameterized, it means that the value is either C<undef> or the
71 parameterized type. So C<Maybe[Int]> means an integer or C<undef>.
73 For more details on the type hierarchy, see
74 L<Moose::Util::TypeConstraints>.
76 =head1 WHAT IS A TYPE?
78 It's important to realize that types are not classes (or
79 packages). Types are just objects (L<Moose::Meta::TypeConstraint>
80 objects, to be exact) with a name and a constraint. Moose maintains a
81 global type registry that lets it convert names like C<Num> into the
84 However, class names I<can be> type names. When you define a new class
85 using Moose, it defines an associated type name behind the scenes:
91 Now you can use C<'MyApp::User'> as a type name:
98 However, for non-Moose classes there's no magic. You may have to
99 explicitly declare the class type. This is a bit muddled because Moose
100 assumes that any unknown type name passed as the C<isa> value for an
101 attribute is a class. So this works:
103 has 'birth_date' => (
108 In general, when Moose is presented with an unknown name, it assumes
109 that the name is a class:
111 subtype 'ModernDateTime'
113 => where { $_->year() >= 1980 }
114 => message { 'The date you provided is not modern enough' };
116 has 'valid_dates' => (
118 isa => 'ArrayRef[DateTime]',
121 Moose will assume that C<DateTime> is a class name in both of these
126 Moose uses subtypes in its built-in hierarchy. For example, C<Int> is
129 A subtype is defined in terms of a parent type and a constraint. Any
130 constraints defined by the parent(s) will be checked first, followed by
131 constraints defined by the subtype. A value must pass I<all> of these
132 checks to be valid for the subtype.
134 Typically, a subtype takes the parent's constraint and makes it more
137 A subtype can also define its own constraint failure message. This
138 lets you do things like have an error "The value you provided (20),
139 was not a valid rating, which must be a number from 1-10." This is
140 much friendlier than the default error, which just says that the value
141 failed a validation check for the type.
143 Here's a simple (and useful) subtype example:
145 subtype 'PositiveInt'
148 => message { "The number you provided, $_, was not a positive number" }
150 Note that the sugar functions for working with types are all exported
151 by L<Moose::Util::TypeConstraints>.
153 =head2 Creating a new type (that isn't a subtype)
155 You can also create new top-level types:
157 type 'FourCharacters' => where { defined $_ && length $_ == 4 };
159 In practice, this example is more or less the same as subtyping
160 C<Str>, except you have to check definedness yourself.
162 It's hard to find a case where you wouldn't want to subtype a very
163 broad type like C<Defined>, C<Ref> or C<Object>.
165 Defining a new top-level type is conceptually the same as subtyping
170 Type names are global throughout the current Perl
171 interpreter. Internally, Moose maps names to type objects via a
172 L<registry|Moose::Meta::TypeConstraint::Registry>.
174 If you have multiple apps or libraries all using Moose in the same
175 process, you could have problems with collisions. We recommend that
176 you prefix names with some sort of namespace indicator to prevent
177 these sorts of collisions.
179 For example, instead of calling a type "PositiveInt", call it
180 "MyApp::Type::PositiveInt" or "MyApp::Types::PositiveInt". We
181 recommend that you centralize all of these definitions in a single
182 package, C<MyApp::Types>, which can be loaded by other classes in your
185 Once you're doing this, you should almost certainly look at the
186 L<MooseX::Types> extension which allows easy declaration of type libraries
187 and can export your types as perl constants so that you can refer to them
190 has 'counter' => (is => 'rw', isa => PositiveInt);
192 rather than needing to fully qualify them everywhere. It also allows
194 has 'counts' => (is => 'ro', isa => HashRef[PositiveInt]);
196 and similarly for the union and other syntax discussed below, which
197 will compile time check your use of names and is generally more robust
198 than the string type parsing for complex cases.
202 One of the most powerful features of Moose's type system is its
203 coercions. A coercion is a way to convert from one type to another.
205 subtype 'ArrayRefOfInts'
206 => as 'ArrayRef[Int]';
208 coerce 'ArrayRefOfInts'
212 You'll note that we had to create a subtype rather than coercing
213 C<ArrayRef[Int]> directly. This is just a quirk of how Moose
216 Coercions, like type names, are global. This is I<another> reason why
217 it is good to namespace your types. Moose will I<never> try to coerce
218 a value unless you explicitly ask for it. This is done by setting the
219 C<coerce> attribute option to a true value:
225 isa => 'ArrayRefOfInts',
229 Foo->new( sizes => 42 );
231 This code example will do the right thing, and the newly created
232 object will have C<[ 42 ]> as its C<sizes> attribute.
236 Deep coercion is the coercion of type parameters for parameterized
237 types. Let's take these types as an example:
241 => where { /[a-f0-9]/i };
249 isa => 'ArrayRef[Int]',
253 If we try passing an array reference of hex numbers for the C<sizes>
254 attribute, Moose will not do any coercion.
256 However, you can define a set of subtypes to enable coercion between
257 two parameterized types.
259 subtype 'ArrayRefOfHexNums'
260 => as 'ArrayRef[HexNum]';
262 subtype 'ArrayRefOfInts'
263 => as 'ArrayRef[Int]';
265 coerce 'ArrayRefOfInts'
266 => from 'ArrayRefOfHexNums'
267 => via { [ map { hex } @{$_} ] };
269 Foo->new( sizes => [ 'a1', 'ff', '22' ] );
271 Now Moose will coerce the hex numbers to integers.
273 However, Moose does not attempt to chain coercions, so it will not
274 coerce a single hex number. To do that, we need to define a separate
277 coerce 'ArrayRefOfInts'
279 => via { [ hex $_ ] };
281 Yes, this can all get verbose, but coercion is tricky magic, and we
282 think it's best to make it explicit.
286 Moose allows you to say that an attribute can be of two or more
287 disparate types. For example, we might allow an C<Object> or
292 isa => 'Object | FileHandle',
295 Moose actually parses that string and recognizes that you are creating
296 a type union. The C<output> attribute will accept any sort of object,
297 as well as an unblessed file handle. It is up to you to do the right
298 thing for each of them in your code.
300 Whenever you use a type union, you should consider whether or not
301 coercion might be a better answer.
303 For our example above, we might want to be more specific, and insist
304 that output be an object with a C<print> method:
308 => where { $_->can('print') };
310 We can coerce file handles to an object that satisfies this condition
311 with a simple wrapper class:
324 my $fh = $self->handle();
329 Now we can define a coercion from C<FileHandle> to our wrapper class:
333 => via { FHWrapper->new( handle => $_ ) };
341 This pattern of using a coercion instead of a type union will help
342 make your class internals simpler.
344 =head1 TYPE CREATION HELPERS
346 The L<Moose::Util::TypeConstraints> module exports a number of helper
347 functions for creating specific kinds of types. These include
348 C<class_type>, C<role_type>, and C<maybe_type>. See the docs for
351 One helper worth noting is C<enum>, which allows you to create a
352 subtype of C<Str> that only allows the specified values:
354 enum 'RGB' => qw( red green blue );
356 This creates a type named C<RGB>.
358 =head1 ANONYMOUS TYPES
360 All of the type creation functions return a type object. This type
361 object can be used wherever you would use a type name, as a parent
362 type, or as the value for an attribute's C<isa> option:
366 isa => subtype('Int' => where { $_ > 0 }),
369 This is handy when you want to create a one-off type and don't want to
370 "pollute" the global namespace registry.
372 =head1 VALIDATING METHOD PARAMETERS
374 Moose does not provide any means of validating method
375 parameters. However, there are several MooseX extensions on CPAN which
378 The simplest and least sugary is L<MooseX::Params::Validate>. This
379 lets you validate a set of named parameters using Moose types:
382 use MooseX::Params::Validate;
386 my %params = validated_hash(
388 bar => { isa => 'Str', default => 'Moose' },
393 L<MooseX::Params::Validate> also supports coercions.
395 There are several more powerful extensions that support method
396 parameter validation using Moose types, including
397 L<MooseX::Method::Signatures>, which gives you a full-blown C<method>
400 method morning (Str $name) {
401 $self->say("Good morning ${name}!");
404 =head1 LOAD ORDER ISSUES
406 Because Moose types are defined at runtime, you may run into load
407 order problems. In particular, you may want to use a class's type
408 constraint before that type has been defined.
410 We have several recommendations for ameliorating this problem. First,
411 define I<all> of your custom types in one module,
412 C<MyApp::Types>. Second, load this module in all of your other
415 If you are still having load order problems, you can make use of the
416 C<find_type_constraint> function exported by
417 L<Moose::Util::TypeConstraints>:
419 class_type('MyApp::User')
420 unless find_type_constraint('MyApp::User');
422 This sort of "find or create" logic is simple to write, and will let
423 you work around load order issues.
427 Dave Rolsky E<lt>autarch@urth.orgE<gt>
429 =head1 COPYRIGHT AND LICENSE
431 Copyright 2009 by Infinity Interactive, Inc.
433 L<http://www.iinteractive.com>
435 This library is free software; you can redistribute it and/or modify
436 it under the same terms as Perl itself.