1Type::Tiny::Manual::UsiUnsgeWritChoMnotor3i(b3u)ted PerlTyDpoec:u:mTeinntya:t:iMoannual::UsingWithMoo3(3)
2
3
4
6 Type::Tiny::Manual::UsingWithMoo3 - alternative use of Type::Tiny with
7 Moo
8
10 Type Registries
11 In all the examples so far, we have imported a collection of type
12 constraints into each class:
13
14 package Horse {
15 use Moo;
16 use Types::Standard qw( Str ArrayRef HashRef Int Any InstanceOf );
17 use Types::Common::Numeric qw( PositiveInt );
18 use Types::Common::String qw( NonEmptyStr );
19
20 has name => ( is => 'ro', isa => Str );
21 has father => ( is => 'ro', isa => InstanceOf["Horse"] );
22 ...;
23 }
24
25 This creates a bunch of subs in the Horse namespace, one for each type.
26 We've used namespace::autoclean to clean these up later.
27
28 But it is also possible to avoid pulling all these into the Horse
29 namespace. Instead we'll use a type registry:
30
31 package Horse {
32 use Moo;
33 use Type::Registry qw( t );
34
35 t->add_types('-Standard');
36 t->add_types('-Common::String');
37 t->add_types('-Common::Numeric');
38
39 t->alias_type('InstanceOf["Horse"]' => 'Horsey');
40
41 has name => ( is => 'ro', isa => t('Str') );
42 has father => ( is => 'ro', isa => t('Horsey') );
43 has mother => ( is => 'ro', isa => t('Horsey') );
44 has children => ( is => 'ro', isa => t('ArrayRef[Horsey]') );
45 ...;
46 }
47
48 You don't even need to import the "t()" function. Types::Registry can
49 be used in an entirely object-oriented way.
50
51 package Horse {
52 use Moo;
53 use Type::Registry;
54
55 my $reg = Type::Registry->for_me;
56
57 $reg->add_types('-Standard');
58 $reg->add_types('-Common::String');
59 $reg->add_types('-Common::Numeric');
60
61 $reg->alias_type('InstanceOf["Horse"]' => 'Horsey');
62
63 has name => ( is => 'ro', isa => $reg->lookup('Str') );
64 ...;
65 }
66
67 You could create two registries with entirely different definitions for
68 the same named type.
69
70 my $dracula = Aristocrat->new(name => 'Dracula');
71
72 package AristocracyTracker {
73 use Type::Registry;
74
75 my $reg1 = Type::Registry->new;
76 $reg1->add_types('-Common::Numeric');
77 $reg1->alias_type('PositiveInt' => 'Count');
78
79 my $reg2 = Type::Registry->new;
80 $reg2->add_types('-Standard');
81 $reg2->alias_type('InstanceOf["Aristocrat"]' => 'Count');
82
83 $reg1->lookup("Count")->assert_valid("1");
84 $reg2->lookup("Count")->assert_valid($dracula);
85 }
86
87 Type::Registry uses "AUTOLOAD", so things like this work:
88
89 $reg->ArrayRef->of( $reg->Int );
90
91 Although you can create as many registries as you like, Type::Registry
92 will create a default registry for each package.
93
94 # Create a new empty registry.
95 #
96 my $reg = Type::Registry->new;
97
98 # Get the default registry for my package.
99 # It will be pre-populated with any types we imported using `use`.
100 #
101 my $reg = Type::Registry->for_me;
102
103 # Get the default registry for some other package.
104 #
105 my $reg = Type::Registry->for_class("Horse");
106
107 Type registries are a convenient place to store a bunch of types
108 without polluting your namespace. They are not the same as type
109 libraries though. Types::Standard, Types::Common::String, and
110 Types::Common::Numeric are type libraries; packages that export types
111 for others to use. We will look at how to make one of those later.
112
113 For now, here's the best way to think of the difference:
114
115 • Type registry
116
117 Curate a collection of types for me to use here in this class.
118 This collection is an implementaion detail.
119
120 • Type library
121
122 Export a collection of types to be used across multiple classes.
123 This collection is part of your API.
124
125 Importing Functions
126 We've seen how, for instance, Types::Standard exports a sub called
127 "Int" that returns the Int type object.
128
129 use Types::Standard qw( Int );
130
131 my $type = Int;
132 $type->check($value) or die $type->get_message($value);
133
134 Type libraries are also capable of exporting other convenience
135 functions.
136
137 "is_*"
138
139 This is a shortcut for checking a value meets a type constraint:
140
141 use Types::Standard qw( is_Int );
142
143 if ( is_Int($value) ) {
144 ...;
145 }
146
147 Calling "is_Int($value)" will often be marginally faster than calling
148 "Int->check($value)" because it avoids a method call. (Method calls in
149 Perl end up slower than normal function calls.)
150
151 Using things like "is_ArrayRef" in your code might be preferable to
152 "ref($value) eq "ARRAY"" because it's neater, leads to more consistent
153 type checking, and might even be faster. (Type::Tiny can be pretty
154 fast; it is sometimes able to export these functions as XS subs.)
155
156 If checking type constraints like "is_ArrayRef" or "is_InstanceOf",
157 there's no way to give a parameter. "is_ArrayRef[Int]($value)" doesn't
158 work, and neither does "is_ArrayRef(Int, $value)" nor
159 "is_ArrayRef($value, Int)". For some types like "is_InstanceOf", this
160 makes them fairly useless; without being able to give a class name, it
161 just acts the same as "is_Object". See "Exporting Parameterized Types"
162 for a solution. Also, check out isa.
163
164 There also exists a generic "is" function.
165
166 use Types::Standard qw( ArrayRef Int );
167 use Type::Utils qw( is );
168
169 if ( is ArrayRef[Int], \@numbers ) {
170 ...;
171 }
172
173 "assert_*"
174
175 While "is_Int($value)" returns a boolean, "assert_Int($value)" will
176 throw an error if the value does not meet the constraint, and return
177 the value otherwise. So you can do:
178
179 my $sum = assert_Int($x) + assert_Int($y);
180
181 And you will get the sum of integers $x and $y, and an explosion if
182 either of them is not an integer!
183
184 Assert is useful for quick parameter checks if you are avoiding
185 Type::Params for some strange reason:
186
187 sub add_numbers {
188 my $x = assert_Num(shift);
189 my $y = assert_Num(shift);
190 return $x + $y;
191 }
192
193 You can also use a generic "assert" function.
194
195 use Type::Utils qw( assert );
196
197 sub add_numbers {
198 my $x = assert Num, shift;
199 my $y = assert Num, shift;
200 return $x + $y;
201 }
202
203 "to_*"
204
205 This is a shortcut for coercion:
206
207 my $truthy = to_Bool($value);
208
209 It trusts that the coercion has worked okay. You can combine it with an
210 assertion if you want to make sure.
211
212 my $truthy = assert_Bool(to_Bool($value));
213
214 Shortcuts for exporting functions
215
216 This is a little verbose:
217
218 use Types::Standard qw( Bool is_Bool assert_Bool to_Bool );
219
220 Isn't this a little bit nicer?
221
222 use Types::Standard qw( +Bool );
223
224 The plus sign tells a type library to export not only the type itself,
225 but all of the convenience functions too.
226
227 You can also use:
228
229 use Types::Standard -types; # export Int, Bool, etc
230 use Types::Standard -is; # export is_Int, is_Bool, etc
231 use Types::Standard -assert; # export assert_Int, assert_Bool, etc
232 use Types::Standard -to; # export to_Bool, etc
233 use Types::Standard -all; # just export everything!!!
234
235 So if you imagine the functions exported by Types::Standard are like
236 this:
237
238 qw(
239 Str is_Str assert_Str
240 Num is_Num assert_Num
241 Int is_Int assert_Int
242 Bool is_Bool assert_Bool to_Bool
243 ArrayRef is_ArrayRef assert_ArrayRef
244 );
245 # ... and more
246
247 Then "+" exports a horizonal group of those, and "-" exports a vertical
248 group.
249
250 Exporting Parameterized Types
251 It's possible to export parameterizable types like ArrayRef, but it is
252 also possible to export parameterized types.
253
254 use Types::Standard qw( ArrayRef Int );
255 use Types::Standard (
256 '+ArrayRef' => { of => Int, -as => 'IntList' },
257 );
258
259 has numbers => (is => 'ro', isa => IntList);
260
261 Using "is_IntList($value)" should be significantly faster than
262 "ArrayRef->of(Int)->check($value)".
263
264 This trick only works for parameterized types that have a single
265 parameter, like ArrayRef, HashRef, InstanceOf, etc. (Sorry, "Dict" and
266 "Tuple"!)
267
268 Do What I Mean!
269 use Type::Utils qw( dwim_type );
270
271 dwim_type("ArrayRef[Int]")
272
273 "dwim_type" will look up a type constraint from a string and attempt to
274 guess what you meant.
275
276 If it's a type constraint that you seem to have imported with "use",
277 then it should find it. Otherwise, if you're using Moose or Mouse,
278 it'll try asking those. Or if it's in Types::Standard, it'll look
279 there. And if it still has no idea, then it will assume
280 dwim_type("Foo") means dwim_type("InstanceOf['Foo']").
281
282 It just does a big old bunch of guessing.
283
284 The "is" function will use "dwim_type" if you pass it a string as a
285 type.
286
287 use Type::Utils qw( is );
288
289 if ( is "ArrayRef[Int]", \@numbers ) {
290 ...;
291 }
292
294 You now know pretty much everything there is to know about how to use
295 type libraries.
296
297 Here's your next step:
298
299 • Type::Tiny::Manual::Libraries
300
301 Defining your own type libraries, including extending existing
302 libraries, defining new types, adding coercions, defining
303 parameterizable types, and the declarative style.
304
306 Toby Inkster <tobyink@cpan.org>.
307
309 This software is copyright (c) 2013-2014, 2017-2021 by Toby Inkster.
310
311 This is free software; you can redistribute it and/or modify it under
312 the same terms as the Perl 5 programming language system itself.
313
315 THIS PACKAGE IS PROVIDED "AS IS" AND WITHOUT ANY EXPRESS OR IMPLIED
316 WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF
317 MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
318
319
320
321perl v5.34.0 2022-01-2T1ype::Tiny::Manual::UsingWithMoo3(3)