.\" Automatically generated by Pod::Man 4.14 (Pod::Simple 3.40) .\" .\" Standard preamble: .\" ======================================================================== .de Sp \" Vertical space (when we can't use .PP) .if t .sp .5v .if n .sp .. .de Vb \" Begin verbatim text .ft CW .nf .ne \\$1 .. .de Ve \" End verbatim text .ft R .fi .. .\" Set up some character translations and predefined strings. \*(-- will .\" give an unbreakable dash, \*(PI will give pi, \*(L" will give a left .\" double quote, and \*(R" will give a right double quote. \*(C+ will .\" give a nicer C++. Capital omega is used to do unbreakable dashes and .\" therefore won't be available. \*(C` and \*(C' expand to `' in nroff, .\" nothing in troff, for use with C<>. .tr \(*W- .ds C+ C\v'-.1v'\h'-1p'\s-2+\h'-1p'+\s0\v'.1v'\h'-1p' .ie n \{\ . ds -- \(*W- . ds PI pi . if (\n(.H=4u)&(1m=24u) .ds -- \(*W\h'-12u'\(*W\h'-12u'-\" diablo 10 pitch . if (\n(.H=4u)&(1m=20u) .ds -- \(*W\h'-12u'\(*W\h'-8u'-\" diablo 12 pitch . ds L" "" . ds R" "" . ds C` "" . ds C' "" 'br\} .el\{\ . ds -- \|\(em\| . ds PI \(*p . ds L" `` . ds R" '' . ds C` . ds C' 'br\} .\" .\" Escape single quotes in literal strings from groff's Unicode transform. .ie \n(.g .ds Aq \(aq .el .ds Aq ' .\" .\" If the F register is >0, we'll generate index entries on stderr for .\" titles (.TH), headers (.SH), subsections (.SS), items (.Ip), and index .\" entries marked with X<> in POD. Of course, you'll have to process the .\" output yourself in some meaningful fashion. .\" .\" Avoid warning from groff about undefined register 'F'. .de IX .. .nr rF 0 .if \n(.g .if rF .nr rF 1 .if (\n(rF:(\n(.g==0)) \{\ . if \nF \{\ . de IX . tm Index:\\$1\t\\n%\t"\\$2" .. . if !\nF==2 \{\ . nr % 0 . nr F 2 . \} . \} .\} .rr rF .\" ======================================================================== .\" .IX Title "Moose::Cookbook::Basics::HTTP_SubtypesAndCoercion 3pm" .TH Moose::Cookbook::Basics::HTTP_SubtypesAndCoercion 3pm "2021-01-04" "perl v5.32.0" "User Contributed Perl Documentation" .\" For nroff, turn off justification. Always turn off hyphenation; it makes .\" way too many mistakes in technical documents. .if n .ad l .nh .SH "NAME" Moose::Cookbook::Basics::HTTP_SubtypesAndCoercion \- Demonstrates subtypes and coercion use HTTP\-related classes (Request, Protocol, etc.) .SH "VERSION" .IX Header "VERSION" version 2.2014 .SH "SYNOPSIS" .IX Header "SYNOPSIS" .Vb 3 \& package Request; \& use Moose; \& use Moose::Util::TypeConstraints; \& \& use HTTP::Headers (); \& use Params::Coerce (); \& use URI (); \& \& subtype \*(AqMy::Types::HTTP::Headers\*(Aq => as class_type(\*(AqHTTP::Headers\*(Aq); \& \& coerce \*(AqMy::Types::HTTP::Headers\*(Aq \& => from \*(AqArrayRef\*(Aq \& => via { HTTP::Headers\->new( @{$_} ) } \& => from \*(AqHashRef\*(Aq \& => via { HTTP::Headers\->new( %{$_} ) }; \& \& subtype \*(AqMy::Types::URI\*(Aq => as class_type(\*(AqURI\*(Aq); \& \& coerce \*(AqMy::Types::URI\*(Aq \& => from \*(AqObject\*(Aq \& => via { $_\->isa(\*(AqURI\*(Aq) \& ? $_ \& : Params::Coerce::coerce( \*(AqURI\*(Aq, $_ ); } \& => from \*(AqStr\*(Aq \& => via { URI\->new( $_, \*(Aqhttp\*(Aq ) }; \& \& subtype \*(AqProtocol\*(Aq \& => as \*(AqStr\*(Aq \& => where { /^HTTP\e/[0\-9]\e.[0\-9]$/ }; \& \& has \*(Aqbase\*(Aq => ( is => \*(Aqrw\*(Aq, isa => \*(AqMy::Types::URI\*(Aq, coerce => 1 ); \& has \*(Aquri\*(Aq => ( is => \*(Aqrw\*(Aq, isa => \*(AqMy::Types::URI\*(Aq, coerce => 1 ); \& has \*(Aqmethod\*(Aq => ( is => \*(Aqrw\*(Aq, isa => \*(AqStr\*(Aq ); \& has \*(Aqprotocol\*(Aq => ( is => \*(Aqrw\*(Aq, isa => \*(AqProtocol\*(Aq ); \& has \*(Aqheaders\*(Aq => ( \& is => \*(Aqrw\*(Aq, \& isa => \*(AqMy::Types::HTTP::Headers\*(Aq, \& coerce => 1, \& default => sub { HTTP::Headers\->new } \& ); .Ve .SH "DESCRIPTION" .IX Header "DESCRIPTION" This recipe introduces type coercions, which are defined with the \&\f(CW\*(C`coerce\*(C'\fR sugar function. Coercions are attached to existing type constraints, and define a (one-way) transformation from one type to another. .PP This is very powerful, but it can also have unexpected consequences, so you have to explicitly ask for an attribute to be coerced. To do this, you must set the \f(CW\*(C`coerce\*(C'\fR attribute option to a true value. .PP First, we create the subtype to which we will coerce the other types: .PP .Vb 1 \& subtype \*(AqMy::Types::HTTP::Headers\*(Aq => as class_type(\*(AqHTTP::Headers\*(Aq); .Ve .PP We are creating a subtype rather than using \f(CW\*(C`HTTP::Headers\*(C'\fR as a type directly. The reason we do this is that coercions are global, and a coercion defined for \f(CW\*(C`HTTP::Headers\*(C'\fR in our \f(CW\*(C`Request\*(C'\fR class would then be defined for \fIall\fR Moose-using classes in the current Perl interpreter. It's a best practice to avoid this sort of namespace pollution. .PP The \f(CW\*(C`class_type\*(C'\fR sugar function is simply a shortcut for this: .PP .Vb 3 \& subtype \*(AqHTTP::Headers\*(Aq \& => as \*(AqObject\*(Aq \& => where { $_\->isa(\*(AqHTTP::Headers\*(Aq) }; .Ve .PP Internally, Moose creates a type constraint for each Moose-using class, but for non-Moose classes, the type must be declared explicitly. .PP We could go ahead and use this new type directly: .PP .Vb 5 \& has \*(Aqheaders\*(Aq => ( \& is => \*(Aqrw\*(Aq, \& isa => \*(AqMy::Types::HTTP::Headers\*(Aq, \& default => sub { HTTP::Headers\->new } \& ); .Ve .PP This creates a simple attribute which defaults to an empty instance of HTTP::Headers. .PP The constructor for HTTP::Headers accepts a list of key-value pairs representing the \s-1HTTP\s0 header fields. In Perl, such a list could be stored in an \s-1ARRAY\s0 or \s-1HASH\s0 reference. We want our \f(CW\*(C`headers\*(C'\fR attribute to accept those data structures instead of an \fBHTTP::Headers\fR instance, and just do the right thing. This is exactly what coercion is for: .PP .Vb 5 \& coerce \*(AqMy::Types::HTTP::Headers\*(Aq \& => from \*(AqArrayRef\*(Aq \& => via { HTTP::Headers\->new( @{$_} ) } \& => from \*(AqHashRef\*(Aq \& => via { HTTP::Headers\->new( %{$_} ) }; .Ve .PP The first argument to \f(CW\*(C`coerce\*(C'\fR is the type \fIto\fR which we are coercing. Then we give it a set of \f(CW\*(C`from\*(C'\fR/\f(CW\*(C`via\*(C'\fR clauses. The \f(CW\*(C`from\*(C'\fR function takes some other type name and \f(CW\*(C`via\*(C'\fR takes a subroutine reference which actually does the coercion. .PP However, defining the coercion doesn't do anything until we tell Moose we want a particular attribute to be coerced: .PP .Vb 6 \& has \*(Aqheaders\*(Aq => ( \& is => \*(Aqrw\*(Aq, \& isa => \*(AqMy::Types::HTTP::Headers\*(Aq, \& coerce => 1, \& default => sub { HTTP::Headers\->new } \& ); .Ve .PP Now, if we use an \f(CW\*(C`ArrayRef\*(C'\fR or \f(CW\*(C`HashRef\*(C'\fR to populate \f(CW\*(C`headers\*(C'\fR, it will be coerced into a new HTTP::Headers instance. With the coercion in place, the following lines of code are all equivalent: .PP .Vb 3 \& $foo\->headers( HTTP::Headers\->new( bar => 1, baz => 2 ) ); \& $foo\->headers( [ \*(Aqbar\*(Aq, 1, \*(Aqbaz\*(Aq, 2 ] ); \& $foo\->headers( { bar => 1, baz => 2 } ); .Ve .PP As you can see, careful use of coercions can produce a very open interface for your class, while still retaining the \*(L"safety\*(R" of your type constraint checks. (1) .PP Our next coercion shows how we can leverage existing \s-1CPAN\s0 modules to help implement coercions. In this case we use Params::Coerce. .PP Once again, we need to declare a class type for our non-Moose \s-1URI\s0 class: .PP .Vb 1 \& subtype \*(AqMy::Types::URI\*(Aq => as class_type(\*(AqURI\*(Aq); .Ve .PP Then we define the coercion: .PP .Vb 7 \& coerce \*(AqMy::Types::URI\*(Aq \& => from \*(AqObject\*(Aq \& => via { $_\->isa(\*(AqURI\*(Aq) \& ? $_ \& : Params::Coerce::coerce( \*(AqURI\*(Aq, $_ ); } \& => from \*(AqStr\*(Aq \& => via { URI\->new( $_, \*(Aqhttp\*(Aq ) }; .Ve .PP The first coercion takes any object and makes it a \f(CW\*(C`URI\*(C'\fR object. The coercion system isn't that smart, and does not check if the object is already a \s-1URI\s0, so we check for that ourselves. If it's not a \s-1URI\s0 already, we let Params::Coerce do its magic, and we just use its return value. .PP If Params::Coerce didn't return a \s-1URI\s0 object (for whatever reason), Moose would throw a type constraint error. .PP The other coercion takes a string and converts it to a \s-1URI\s0. In this case, we are using the coercion to apply a default behavior, where a string is assumed to be an \f(CW\*(C`http\*(C'\fR \s-1URI.\s0 .PP Finally, we need to make sure our attributes enable coercion. .PP .Vb 2 \& has \*(Aqbase\*(Aq => ( is => \*(Aqrw\*(Aq, isa => \*(AqMy::Types::URI\*(Aq, coerce => 1 ); \& has \*(Aquri\*(Aq => ( is => \*(Aqrw\*(Aq, isa => \*(AqMy::Types::URI\*(Aq, coerce => 1 ); .Ve .PP Re-using the coercion lets us enforce a consistent \s-1API\s0 across multiple attributes. .SH "CONCLUSION" .IX Header "CONCLUSION" This recipe showed the use of coercions to create a more flexible and DWIM-y \s-1API.\s0 Like any powerful feature, we recommend some caution. Sometimes it's better to reject a value than just guess at how to \s-1DWIM.\s0 .PP We also showed the use of the \f(CW\*(C`class_type\*(C'\fR sugar function as a shortcut for defining a new subtype of \f(CW\*(C`Object\*(C'\fR. .SH "FOOTNOTES" .IX Header "FOOTNOTES" .IP "(1)" 4 .IX Item "(1)" This particular example could be safer. Really we only want to coerce an array with an \fIeven\fR number of elements. We could create a new \&\f(CW\*(C`EvenElementArrayRef\*(C'\fR type, and then coerce from that type, as opposed to a plain \f(CW\*(C`ArrayRef\*(C'\fR .SH "AUTHORS" .IX Header "AUTHORS" .IP "\(bu" 4 Stevan Little .IP "\(bu" 4 Dave Rolsky .IP "\(bu" 4 Jesse Luehrs .IP "\(bu" 4 Shawn M Moore .IP "\(bu" 4 יובל קוג'מן (Yuval Kogman) .IP "\(bu" 4 Karen Etheridge .IP "\(bu" 4 Florian Ragwitz .IP "\(bu" 4 Hans Dieter Pearcey .IP "\(bu" 4 Chris Prather .IP "\(bu" 4 Matt S Trout .SH "COPYRIGHT AND LICENSE" .IX Header "COPYRIGHT AND LICENSE" This software is copyright (c) 2006 by Infinity Interactive, Inc. .PP This is free software; you can redistribute it and/or modify it under the same terms as the Perl 5 programming language system itself.