1Moose::Cookbook::BasicsU:s:eHrTMTCoPoo_nsSteur:bi:tbCyuoptoeeksdbAonPodekCr:ol:eBrDacosicioucnms(e:3n:)tHaTtTiPo_nSubtypesAndCoercion(3)
2
3
4

NAME

6       Moose::Cookbook::Basics::HTTP_SubtypesAndCoercion - Demonstrates
7       subtypes and coercion use HTTP-related classes (Request, Protocol,
8       etc.)
9

VERSION

11       version 2.2014
12

SYNOPSIS

14         package Request;
15         use Moose;
16         use Moose::Util::TypeConstraints;
17
18         use HTTP::Headers  ();
19         use Params::Coerce ();
20         use URI            ();
21
22         subtype 'My::Types::HTTP::Headers' => as class_type('HTTP::Headers');
23
24         coerce 'My::Types::HTTP::Headers'
25             => from 'ArrayRef'
26                 => via { HTTP::Headers->new( @{$_} ) }
27             => from 'HashRef'
28                 => via { HTTP::Headers->new( %{$_} ) };
29
30         subtype 'My::Types::URI' => as class_type('URI');
31
32         coerce 'My::Types::URI'
33             => from 'Object'
34                 => via { $_->isa('URI')
35                          ? $_
36                          : Params::Coerce::coerce( 'URI', $_ ); }
37             => from 'Str'
38                 => via { URI->new( $_, 'http' ) };
39
40         subtype 'Protocol'
41             => as 'Str'
42             => where { /^HTTP\/[0-9]\.[0-9]$/ };
43
44         has 'base' => ( is => 'rw', isa => 'My::Types::URI', coerce => 1 );
45         has 'uri'  => ( is => 'rw', isa => 'My::Types::URI', coerce => 1 );
46         has 'method'   => ( is => 'rw', isa => 'Str' );
47         has 'protocol' => ( is => 'rw', isa => 'Protocol' );
48         has 'headers'  => (
49             is      => 'rw',
50             isa     => 'My::Types::HTTP::Headers',
51             coerce  => 1,
52             default => sub { HTTP::Headers->new }
53         );
54

DESCRIPTION

56       This recipe introduces type coercions, which are defined with the
57       "coerce" sugar function. Coercions are attached to existing type
58       constraints, and define a (one-way) transformation from one type to
59       another.
60
61       This is very powerful, but it can also have unexpected consequences, so
62       you have to explicitly ask for an attribute to be coerced. To do this,
63       you must set the "coerce" attribute option to a true value.
64
65       First, we create the subtype to which we will coerce the other types:
66
67         subtype 'My::Types::HTTP::Headers' => as class_type('HTTP::Headers');
68
69       We are creating a subtype rather than using "HTTP::Headers" as a type
70       directly. The reason we do this is that coercions are global, and a
71       coercion defined for "HTTP::Headers" in our "Request" class would then
72       be defined for all Moose-using classes in the current Perl interpreter.
73       It's a best practice to avoid this sort of namespace pollution.
74
75       The "class_type" sugar function is simply a shortcut for this:
76
77         subtype 'HTTP::Headers'
78             => as 'Object'
79             => where { $_->isa('HTTP::Headers') };
80
81       Internally, Moose creates a type constraint for each Moose-using class,
82       but for non-Moose classes, the type must be declared explicitly.
83
84       We could go ahead and use this new type directly:
85
86         has 'headers' => (
87             is      => 'rw',
88             isa     => 'My::Types::HTTP::Headers',
89             default => sub { HTTP::Headers->new }
90         );
91
92       This creates a simple attribute which defaults to an empty instance of
93       HTTP::Headers.
94
95       The constructor for HTTP::Headers accepts a list of key-value pairs
96       representing the HTTP header fields. In Perl, such a list could be
97       stored in an ARRAY or HASH reference. We want our "headers" attribute
98       to accept those data structures instead of an HTTP::Headers instance,
99       and just do the right thing. This is exactly what coercion is for:
100
101         coerce 'My::Types::HTTP::Headers'
102             => from 'ArrayRef'
103                 => via { HTTP::Headers->new( @{$_} ) }
104             => from 'HashRef'
105                 => via { HTTP::Headers->new( %{$_} ) };
106
107       The first argument to "coerce" is the type to which we are coercing.
108       Then we give it a set of "from"/"via" clauses. The "from" function
109       takes some other type name and "via" takes a subroutine reference which
110       actually does the coercion.
111
112       However, defining the coercion doesn't do anything until we tell Moose
113       we want a particular attribute to be coerced:
114
115         has 'headers' => (
116             is      => 'rw',
117             isa     => 'My::Types::HTTP::Headers',
118             coerce  => 1,
119             default => sub { HTTP::Headers->new }
120         );
121
122       Now, if we use an "ArrayRef" or "HashRef" to populate "headers", it
123       will be coerced into a new HTTP::Headers instance. With the coercion in
124       place, the following lines of code are all equivalent:
125
126         $foo->headers( HTTP::Headers->new( bar => 1, baz => 2 ) );
127         $foo->headers( [ 'bar', 1, 'baz', 2 ] );
128         $foo->headers( { bar => 1, baz => 2 } );
129
130       As you can see, careful use of coercions can produce a very open
131       interface for your class, while still retaining the "safety" of your
132       type constraint checks. (1)
133
134       Our next coercion shows how we can leverage existing CPAN modules to
135       help implement coercions. In this case we use Params::Coerce.
136
137       Once again, we need to declare a class type for our non-Moose URI
138       class:
139
140         subtype 'My::Types::URI' => as class_type('URI');
141
142       Then we define the coercion:
143
144         coerce 'My::Types::URI'
145             => from 'Object'
146                 => via { $_->isa('URI')
147                          ? $_
148                          : Params::Coerce::coerce( 'URI', $_ ); }
149             => from 'Str'
150                 => via { URI->new( $_, 'http' ) };
151
152       The first coercion takes any object and makes it a "URI" object. The
153       coercion system isn't that smart, and does not check if the object is
154       already a URI, so we check for that ourselves. If it's not a URI
155       already, we let Params::Coerce do its magic, and we just use its return
156       value.
157
158       If Params::Coerce didn't return a URI object (for whatever reason),
159       Moose would throw a type constraint error.
160
161       The other coercion takes a string and converts it to a URI. In this
162       case, we are using the coercion to apply a default behavior, where a
163       string is assumed to be an "http" URI.
164
165       Finally, we need to make sure our attributes enable coercion.
166
167         has 'base' => ( is => 'rw', isa => 'My::Types::URI', coerce => 1 );
168         has 'uri'  => ( is => 'rw', isa => 'My::Types::URI', coerce => 1 );
169
170       Re-using the coercion lets us enforce a consistent API across multiple
171       attributes.
172

CONCLUSION

174       This recipe showed the use of coercions to create a more flexible and
175       DWIM-y API. Like any powerful feature, we recommend some caution.
176       Sometimes it's better to reject a value than just guess at how to DWIM.
177
178       We also showed the use of the "class_type" sugar function as a shortcut
179       for defining a new subtype of "Object".
180

FOOTNOTES

182       (1) This particular example could be safer. Really we only want to
183           coerce an array with an even number of elements. We could create a
184           new "EvenElementArrayRef" type, and then coerce from that type, as
185           opposed to a plain "ArrayRef"
186

AUTHORS

188       •   Stevan Little <stevan@cpan.org>
189
190       •   Dave Rolsky <autarch@urth.org>
191
192       •   Jesse Luehrs <doy@cpan.org>
193
194       •   Shawn M Moore <sartak@cpan.org>
195
196       •   יובל קוג'מן (Yuval Kogman) <nothingmuch@woobling.org>
197
198       •   Karen Etheridge <ether@cpan.org>
199
200       •   Florian Ragwitz <rafl@debian.org>
201
202       •   Hans Dieter Pearcey <hdp@cpan.org>
203
204       •   Chris Prather <chris@prather.org>
205
206       •   Matt S Trout <mstrout@cpan.org>
207
209       This software is copyright (c) 2006 by Infinity Interactive, Inc.
210
211       This is free software; you can redistribute it and/or modify it under
212       the same terms as the Perl 5 programming language system itself.
213
214
215
216perl v5.32.1              Moose::C2o0o2k1b-o0o1k-:2:7Basics::HTTP_SubtypesAndCoercion(3)
Impressum