1MooseX::Types(3) User Contributed Perl Documentation MooseX::Types(3)
2
3
4
6 MooseX::Types - Organise your Moose types in libraries
7
9 Library Definition
10 package MyLibrary;
11
12 # predeclare our own types
13 use MooseX::Types
14 -declare => [qw(
15 PositiveInt NegativeInt
16 ArrayRefOfPositiveInt ArrayRefOfAtLeastThreeNegativeInts
17 LotsOfInnerConstraints StrOrArrayRef
18 MyDateTime
19 )];
20
21 # import builtin types
22 use MooseX::Types::Moose qw/Int HashRef/;
23
24 # type definition.
25 subtype PositiveInt,
26 as Int,
27 where { $_ > 0 },
28 message { "Int is not larger than 0" };
29
30 subtype NegativeInt,
31 as Int,
32 where { $_ < 0 },
33 message { "Int is not smaller than 0" };
34
35 # type coercion
36 coerce PositiveInt,
37 from Int,
38 via { 1 };
39
40 # with parameterized constraints.
41
42 subtype ArrayRefOfPositiveInt,
43 as ArrayRef[PositiveInt];
44
45 subtype ArrayRefOfAtLeastThreeNegativeInts,
46 as ArrayRef[NegativeInt],
47 where { scalar(@$_) > 2 };
48
49 subtype LotsOfInnerConstraints,
50 as ArrayRef[ArrayRef[HashRef[Int]]];
51
52 # with TypeConstraint Unions
53
54 subtype StrOrArrayRef,
55 as Str|ArrayRef;
56
57 # class types
58
59 class_type 'DateTime';
60
61 # or better
62
63 class_type MyDateTime, { class => 'DateTime' };
64
65 coerce MyDateTime,
66 from HashRef,
67 via { DateTime->new(%$_) };
68
69 1;
70
71 Usage
72 package Foo;
73 use Moose;
74 use MyLibrary qw( PositiveInt NegativeInt );
75
76 # use the exported constants as type names
77 has 'bar',
78 isa => PositiveInt,
79 is => 'rw';
80 has 'baz',
81 isa => NegativeInt,
82 is => 'rw';
83
84 sub quux {
85 my ($self, $value);
86
87 # test the value
88 print "positive\n" if is_PositiveInt($value);
89 print "negative\n" if is_NegativeInt($value);
90
91 # coerce the value, NegativeInt doesn't have a coercion
92 # helper, since it didn't define any coercions.
93 $value = to_PositiveInt($value) or die "Cannot coerce";
94 }
95
96 1;
97
99 The types provided with Moose are by design global. This package helps
100 you to organise and selectively import your own and the built-in types
101 in libraries. As a nice side effect, it catches typos at compile-time
102 too.
103
104 However, the main reason for this module is to provide an easy way to
105 not have conflicts with your type names, since the internal fully
106 qualified names of the types will be prefixed with the library's name.
107
108 This module will also provide you with some helper functions to make it
109 easier to use Moose types in your code.
110
111 String type names will produce a warning, unless it's for a
112 "class_type" or "role_type" declared within the library, or a fully
113 qualified name like 'MyTypeLibrary::Foo'.
114
116 $type
117 A constant with the name of your type. It contains the type's fully
118 qualified name. Takes no value, as all constants.
119
120 is_$type
121 This handler takes a value and tests if it is a valid value for this
122 $type. It will return true or false.
123
124 to_$type
125 A handler that will take a value and coerce it into the $type. It will
126 return a false value if the type could not be coerced.
127
128 Important Note: This handler will only be exported for types that can
129 do type coercion. This has the advantage that a coercion to a type that
130 cannot hasn't defined any coercions will lead to a compile-time error.
131
133 A MooseX::Types is just a normal Perl module. Unlike Moose itself, it
134 does not install "use strict" and "use warnings" in your class by
135 default, so this is up to you.
136
137 The only thing a library is required to do is
138
139 use MooseX::Types -declare => \@types;
140
141 with @types being a list of types you wish to define in this library.
142 This line will install a proper base class in your package as well as
143 the full set of handlers for your declared types. It will then hand
144 control over to Moose::Util::TypeConstraints' "import" method to export
145 the functions you will need to declare your types.
146
147 If you want to use Moose' built-in types (e.g. for subtyping) you will
148 want to
149
150 use MooseX::Types::Moose @types;
151
152 to import the helpers from the shipped MooseX::Types::Moose library
153 which can export all types that come with Moose.
154
155 You will have to define coercions for your types or your library won't
156 export a "to_$type" coercion helper for it.
157
158 Note that you currently cannot define types containing "::", since
159 exporting would be a problem.
160
161 You also don't need to use "warnings" and "strict", since the
162 definition of a library automatically exports those.
163
165 You can import the "type helpers" of a library by "use"ing it with a
166 list of types to import as arguments. If you want all of them, use the
167 ":all" tag. For example:
168
169 use MyLibrary ':all';
170 use MyOtherLibrary qw( TypeA TypeB );
171
172 MooseX::Types comes with a library of Moose' built-in types called
173 MooseX::Types::Moose.
174
175 The exporting mechanism is, since version 0.5, implemented via a
176 wrapper around Sub::Exporter. This means you can do something like
177 this:
178
179 use MyLibrary TypeA => { -as => 'MyTypeA' },
180 TypeB => { -as => 'MyTypeB' };
181
183 You can define your own wrapper subclasses to manipulate the behaviour
184 of a set of library exports. Here is an example:
185
186 package MyWrapper;
187 use strict;
188 use MRO::Compat;
189 use base 'MooseX::Types::Wrapper';
190
191 sub coercion_export_generator {
192 my $class = shift;
193 my $code = $class->next::method(@_);
194 return sub {
195 my $value = $code->(@_);
196 warn "Coercion returned undef!"
197 unless defined $value;
198 return $value;
199 };
200 }
201
202 1;
203
204 This class wraps the coercion generator (e.g., "to_Int()") and warns if
205 a coercion returned an undefined value. You can wrap any library with
206 this:
207
208 package Foo;
209 use strict;
210 use MyWrapper MyLibrary => [qw( Foo Bar )],
211 Moose => [qw( Str Int )];
212
213 ...
214 1;
215
216 The "Moose" library name is a special shortcut for
217 MooseX::Types::Moose.
218
219 Generator methods you can overload
220 type_export_generator( $short, $full )
221 Creates a closure returning the type's Moose::Meta::TypeConstraint
222 object.
223
224 check_export_generator( $short, $full, $undef_message )
225 This creates the closure used to test if a value is valid for this
226 type.
227
228 coercion_export_generator( $short, $full, $undef_message )
229 This is the closure that's doing coercions.
230
231 Provided Parameters
232 $short
233 The short, exported name of the type.
234
235 $full
236 The fully qualified name of this type as Moose knows it.
237
238 $undef_message
239 A message that will be thrown when type functionality is used but
240 the type does not yet exist.
241
243 As of version 0.08, Moose::Types has experimental support for Recursive
244 subtypes. This will allow:
245
246 subtype Tree() => as HashRef[Str|Tree];
247
248 Which validates things like:
249
250 {key=>'value'};
251 {key=>{subkey1=>'value', subkey2=>'value'}}
252
253 And so on. This feature is new and there may be lurking bugs so don't
254 be afraid to hunt me down with patches and test cases if you have
255 trouble.
256
258 MooseX::Types uses MooseX::Types::TypeDecorator to do some overloading
259 which generally allows you to easily create union types:
260
261 subtype StrOrArrayRef,
262 as Str|ArrayRef;
263
264 As with parameterized constrains, this overloading extends to modules
265 using the types you define in a type library.
266
267 use Moose;
268 use MooseX::Types::Moose qw(HashRef Int);
269
270 has 'attr' => (isa=>HashRef|Int);
271
272 And everything should just work as you'd think.
273
275 import
276 Installs the MooseX::Types::Base class into the caller and exports
277 types according to the specification described in "LIBRARY DEFINITION".
278 This will continue to Moose::Util::TypeConstraints' "import" method to
279 export helper functions you will need to declare your types.
280
281 type_export_generator
282 Generate a type export, e.g. "Int()". This will return either a
283 Moose::Meta::TypeConstraint object, or alternatively a
284 MooseX::Types::UndefinedType object if the type was not yet defined.
285
286 create_arged_type_constraint ($name, @args)
287 Given a String $name with @args find the matching typeconstraint and
288 parameterize it with @args.
289
290 create_base_type_constraint ($name)
291 Given a String $name, find the matching typeconstraint.
292
293 create_type_decorator ($type_constraint)
294 Given a $type_constraint, return a lightweight
295 MooseX::Types::TypeDecorator instance.
296
297 coercion_export_generator
298 This generates a coercion handler function, e.g. "to_Int($value)".
299
300 check_export_generator
301 Generates a constraint check closure, e.g. "is_Int($value)".
302
304 The following are lists of gotcha's and their workarounds for
305 developers coming from the standard string based type constraint names
306
307 Uniqueness
308 A library makes the types quasi-unique by prefixing their names with
309 (by default) the library package name. If you're only using the type
310 handler functions provided by MooseX::Types, you shouldn't ever have to
311 use a type's actual full name.
312
313 Argument separation ('=>' versus ',')
314 The Perlop manpage has this to say about the '=>' operator: "The =>
315 operator is a synonym for the comma, but forces any word (consisting
316 entirely of word characters) to its left to be interpreted as a string
317 (as of 5.001). This includes words that might otherwise be considered a
318 constant or function call."
319
320 Due to this stringification, the following will NOT work as you might
321 think:
322
323 subtype StrOrArrayRef => as Str|ArrayRef;
324
325 The 'StrOrArrayRef' will have it's stringification activated this
326 causes the subtype to not be created. Since the bareword type
327 constraints are not strings you really should not try to treat them
328 that way. You will have to use the ',' operator instead. The author's
329 of this package realize that all the Moose documention and examples
330 nearly uniformly use the '=>' version of the comma operator and this
331 could be an issue if you are converting code.
332
333 Patches welcome for discussion.
334
335 Compatibility with Sub::Exporter
336 If you want to use Sub::Exporter with a Type Library, you need to make
337 sure you export all the type constraints declared AS WELL AS any
338 additional export targets. For example if you do:
339
340 package TypeAndSubExporter; {
341
342 use MooseX::Types::Moose qw(Str);
343 use MooseX::Types -declare => [qw(MyStr)];
344 use Sub::Exporter -setup => { exports => [ qw(something) ] };
345
346 subtype MyStr,
347 as Str;
348
349 sub something {
350 return 1;
351 }
352
353 } 1;
354
355 package Foo; {
356 use TypeAndSubExporter qw(MyStr);
357 } 1;
358
359 You'll get a '"MyStr" is not exported by the TypeAndSubExporter module'
360 error. Upi can workaround by:
361
362 - use Sub::Exporter -setup => { exports => [ qw(something) ] };
363 + use Sub::Exporter -setup => { exports => [ qw(something MyStr) ] };
364
365 This is a workaround and I am exploring how to make these modules work
366 better together. I realize this workaround will lead a lot of
367 duplication in your export declarations and will be onerous for large
368 type libraries. Patches and detailed test cases welcome. See the tests
369 directory for a start on this.
370
372 Moose, Moose::Util::TypeConstraints, MooseX::Types::Moose,
373 Sub::Exporter
374
376 Many thanks to the "#moose" cabal on "irc.perl.org".
377
379 Robert "phaylon" Sedlacek <rs@474.at>
380
382 jnapiorkowski: John Napiorkowski <jjnapiork@cpan.org>
383
384 caelum: Rafael Kitover <rkitover@cpan.org>
385
386 rafl: Florian Ragwitz <rafl@debian.org>
387
388 hdp: Hans Dieter Pearcey <hdp@cpan.org>
389
390 autarch: Dave Rolsky <autarch@urth.org>
391
393 Copyright (c) 2007-2009 Robert Sedlacek <rs@474.at>
394
395 This program is free software; you can redistribute it and/or modify it
396 under the same terms as perl itself.
397
398
399
400perl v5.12.1 2010-06-01 MooseX::Types(3)