.\" Automatically generated by Pod::Man 2.22 (Pod::Simple 3.07)
.\"
.\" 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" ''
'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 turned on, 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.
.ie \nF \{\
. de IX
. tm Index:\\$1\t\\n%\t"\\$2"
..
. nr % 0
. rr F
.\}
.el \{\
. de IX
..
.\}
.\"
.\" Accent mark definitions (@(#)ms.acc 1.5 88/02/08 SMI; from UCB 4.2).
.\" Fear. Run. Save yourself. No user-serviceable parts.
. \" fudge factors for nroff and troff
.if n \{\
. ds #H 0
. ds #V .8m
. ds #F .3m
. ds #[ \f1
. ds #] \fP
.\}
.if t \{\
. ds #H ((1u-(\\\\n(.fu%2u))*.13m)
. ds #V .6m
. ds #F 0
. ds #[ \&
. ds #] \&
.\}
. \" simple accents for nroff and troff
.if n \{\
. ds ' \&
. ds ` \&
. ds ^ \&
. ds , \&
. ds ~ ~
. ds /
.\}
.if t \{\
. ds ' \\k:\h'-(\\n(.wu*8/10-\*(#H)'\'\h"|\\n:u"
. ds ` \\k:\h'-(\\n(.wu*8/10-\*(#H)'\`\h'|\\n:u'
. ds ^ \\k:\h'-(\\n(.wu*10/11-\*(#H)'^\h'|\\n:u'
. ds , \\k:\h'-(\\n(.wu*8/10)',\h'|\\n:u'
. ds ~ \\k:\h'-(\\n(.wu-\*(#H-.1m)'~\h'|\\n:u'
. ds / \\k:\h'-(\\n(.wu*8/10-\*(#H)'\z\(sl\h'|\\n:u'
.\}
. \" troff and (daisy-wheel) nroff accents
.ds : \\k:\h'-(\\n(.wu*8/10-\*(#H+.1m+\*(#F)'\v'-\*(#V'\z.\h'.2m+\*(#F'.\h'|\\n:u'\v'\*(#V'
.ds 8 \h'\*(#H'\(*b\h'-\*(#H'
.ds o \\k:\h'-(\\n(.wu+\w'\(de'u-\*(#H)/2u'\v'-.3n'\*(#[\z\(de\v'.3n'\h'|\\n:u'\*(#]
.ds d- \h'\*(#H'\(pd\h'-\w'~'u'\v'-.25m'\f2\(hy\fP\v'.25m'\h'-\*(#H'
.ds D- D\\k:\h'-\w'D'u'\v'-.11m'\z\(hy\v'.11m'\h'|\\n:u'
.ds th \*(#[\v'.3m'\s+1I\s-1\v'-.3m'\h'-(\w'I'u*2/3)'\s-1o\s+1\*(#]
.ds Th \*(#[\s+2I\s-2\h'-\w'I'u*3/5'\v'-.3m'o\v'.3m'\*(#]
.ds ae a\h'-(\w'a'u*4/10)'e
.ds Ae A\h'-(\w'A'u*4/10)'E
. \" corrections for vroff
.if v .ds ~ \\k:\h'-(\\n(.wu*9/10-\*(#H)'\s-2\u~\d\s+2\h'|\\n:u'
.if v .ds ^ \\k:\h'-(\\n(.wu*10/11-\*(#H)'\v'-.4m'^\v'.4m'\h'|\\n:u'
. \" for low resolution devices (crt and lpr)
.if \n(.H>23 .if \n(.V>19 \
\{\
. ds : e
. ds 8 ss
. ds o a
. ds d- d\h'-1'\(ga
. ds D- D\h'-1'\(hy
. ds th \o'bp'
. ds Th \o'LP'
. ds ae ae
. ds Ae AE
.\}
.rm #[ #] #H #V #F C
.\" ========================================================================
.\"
.IX Title "Moose::Cookbook::Basics::HTTP_SubtypesAndCoercion 3"
.TH Moose::Cookbook::Basics::HTTP_SubtypesAndCoercion 3 "2012-05-07" "perl v5.10.1" "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.0602
.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 "AUTHOR"
.IX Header "AUTHOR"
Moose is maintained by the Moose Cabal, along with the help of many contributors. See \*(L"\s-1CABAL\s0\*(R" in Moose and \*(L"\s-1CONTRIBUTORS\s0\*(R" in Moose for details.
.SH "COPYRIGHT AND LICENSE"
.IX Header "COPYRIGHT AND LICENSE"
This software is copyright (c) 2012 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.