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 "assert_*"
157
158 While "is_Int($value)" returns a boolean, "assert_Int($value)" will
159 throw an error if the value does not meet the constraint, and return
160 the value otherwise. So you can do:
161
162 my $sum = assert_Int($x) + assert_Int($y);
163
164 And you will get the sum of integers $x and $y, and an explosion if
165 either of them is not an integer!
166
167 Assert is useful for quick parameter checks if you are avoiding
168 Type::Params for some strange reason:
169
170 sub add_numbers {
171 my $x = assert_Num(shift);
172 my $y = assert_Num(shift);
173 return $x + $y;
174 }
175
176 "to_*"
177
178 This is a shortcut for coercion:
179
180 my $truthy = to_Bool($value);
181
182 It trusts that the coercion has worked okay. You can combine it with an
183 assertion if you want to make sure.
184
185 my $truthy = assert_Bool(to_Bool($value));
186
187 Shortcuts for exporting functions
188
189 This is a little verbose:
190
191 use Types::Standard qw( Bool is_Bool assert_Bool to_Bool );
192
193 Isn't this a little bit nicer?
194
195 use Types::Standard qw( +Bool );
196
197 The plus sign tells a type library to export not only the type itself,
198 but all of the convenience functions too.
199
200 You can also use:
201
202 use Types::Standard -types; # export Int, Bool, etc
203 use Types::Standard -is; # export is_Int, is_Bool, etc
204 use Types::Standard -assert; # export assert_Int, assert_Bool, etc
205 use Types::Standard -to; # export to_Bool, etc
206 use Types::Standard -all; # just export everything!!!
207
208 So if you imagine the functions exported by Types::Standard are like
209 this:
210
211 qw(
212 Str is_Str assert_Str
213 Num is_Num assert_Num
214 Int is_Int assert_Int
215 Bool is_Bool assert_Bool to_Bool
216 ArrayRef is_ArrayRef assert_ArrayRef
217 );
218 # ... and more
219
220 Then "+" exports a horizonal group of those, and "-" exports a vertical
221 group.
222
223 Exporting Parameterized Types
224 It's possible to export parameterizable types like ArrayRef, but it is
225 also possible to export parameterized types.
226
227 use Types::Standard qw( ArrayRef Int );
228 use Types::Standard (
229 '+ArrayRef' => { of => Int, -as => 'IntList' },
230 );
231
232 has numbers => (is => 'ro', isa => IntList);
233
234 Using "is_IntList($value)" should be significantly faster than
235 "ArrayRef->of(Int)->check($value)".
236
237 This trick only works for parameterized types that have a single
238 parameter, like ArrayRef, HashRef, InstanceOf, etc. (Sorry, "Dict" and
239 "Tuple"!)
240
241 Do What I Mean!
242 use Type::Utils qw( dwim_type );
243
244 dwim_type("ArrayRef[Int]")
245
246 "dwim_type" will look up a type constraint from a string and attempt to
247 guess what you meant.
248
249 If it's a type constraint that you seem to have imported with "use",
250 then it should find it. Otherwise, if you're using Moose or Mouse,
251 it'll try asking those. Or if it's in Types::Standard, it'll look
252 there. And if it still has no idea, then it will assume
253 dwim_type("Foo") means dwim_type("InstanceOf['Foo']").
254
255 It just does a big old bunch of guessing.
256
258 You now know pretty much everything there is to know about how to use
259 type libraries.
260
261 Here's your next step:
262
263 · Type::Tiny::Manual::Libraries
264
265 Defining your own type libraries, including extending existing
266 libraries, defining new types, adding coercions, defining
267 parameterizable types, and the declarative style.
268
270 Toby Inkster <tobyink@cpan.org>.
271
273 This software is copyright (c) 2013-2014, 2017-2020 by Toby Inkster.
274
275 This is free software; you can redistribute it and/or modify it under
276 the same terms as the Perl 5 programming language system itself.
277
279 THIS PACKAGE IS PROVIDED "AS IS" AND WITHOUT ANY EXPRESS OR IMPLIED
280 WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF
281 MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
282
283
284
285perl v5.32.0 2020-09-1T7ype::Tiny::Manual::UsingWithMoo3(3)