{
    "mode": "perldoc",
    "parameter": "Moose::Cookbook::Basics::HTTP_SubtypesAndCoercion",
    "section": "",
    "url": "https://www.chedong.com/phpMan.php/perldoc/Moose%3A%3ACookbook%3A%3ABasics%3A%3AHTTP_SubtypesAndCoercion/json",
    "generated": "2026-11-20T12:38:13Z",
    "synopsis": "package Request;\nuse Moose;\nuse Moose::Util::TypeConstraints;\nuse HTTP::Headers  ();\nuse Params::Coerce ();\nuse URI            ();\nsubtype 'My::Types::HTTP::Headers' => as classtype('HTTP::Headers');\ncoerce 'My::Types::HTTP::Headers'\n=> from 'ArrayRef'\n=> via { HTTP::Headers->new( @{$} ) }\n=> from 'HashRef'\n=> via { HTTP::Headers->new( %{$} ) };\nsubtype 'My::Types::URI' => as classtype('URI');\ncoerce 'My::Types::URI'\n=> from 'Object'\n=> via { $->isa('URI')\n? $\n: Params::Coerce::coerce( 'URI', $ ); }\n=> from 'Str'\n=> via { URI->new( $, 'http' ) };\nsubtype 'Protocol'\n=> as 'Str'\n=> where { /^HTTP\\/[0-9]\\.[0-9]$/ };\nhas 'base' => ( is => 'rw', isa => 'My::Types::URI', coerce => 1 );\nhas 'uri'  => ( is => 'rw', isa => 'My::Types::URI', coerce => 1 );\nhas 'method'   => ( is => 'rw', isa => 'Str' );\nhas 'protocol' => ( is => 'rw', isa => 'Protocol' );\nhas 'headers'  => (\nis      => 'rw',\nisa     => 'My::Types::HTTP::Headers',\ncoerce  => 1,\ndefault => sub { HTTP::Headers->new }\n);",
    "sections": {
        "NAME": {
            "content": "Moose::Cookbook::Basics::HTTPSubtypesAndCoercion - Demonstrates subtypes and coercion use\nHTTP-related classes (Request, Protocol, etc.)\n",
            "subsections": []
        },
        "VERSION": {
            "content": "version 2.2207\n",
            "subsections": []
        },
        "SYNOPSIS": {
            "content": "package Request;\nuse Moose;\nuse Moose::Util::TypeConstraints;\n\nuse HTTP::Headers  ();\nuse Params::Coerce ();\nuse URI            ();\n\nsubtype 'My::Types::HTTP::Headers' => as classtype('HTTP::Headers');\n\ncoerce 'My::Types::HTTP::Headers'\n=> from 'ArrayRef'\n=> via { HTTP::Headers->new( @{$} ) }\n=> from 'HashRef'\n=> via { HTTP::Headers->new( %{$} ) };\n\nsubtype 'My::Types::URI' => as classtype('URI');\n\ncoerce 'My::Types::URI'\n=> from 'Object'\n=> via { $->isa('URI')\n? $\n: Params::Coerce::coerce( 'URI', $ ); }\n=> from 'Str'\n=> via { URI->new( $, 'http' ) };\n\nsubtype 'Protocol'\n=> as 'Str'\n=> where { /^HTTP\\/[0-9]\\.[0-9]$/ };\n\nhas 'base' => ( is => 'rw', isa => 'My::Types::URI', coerce => 1 );\nhas 'uri'  => ( is => 'rw', isa => 'My::Types::URI', coerce => 1 );\nhas 'method'   => ( is => 'rw', isa => 'Str' );\nhas 'protocol' => ( is => 'rw', isa => 'Protocol' );\nhas 'headers'  => (\nis      => 'rw',\nisa     => 'My::Types::HTTP::Headers',\ncoerce  => 1,\ndefault => sub { HTTP::Headers->new }\n);\n",
            "subsections": []
        },
        "DESCRIPTION": {
            "content": "This recipe introduces type coercions, which are defined with the \"coerce\" sugar function.\nCoercions are attached to existing type constraints, and define a (one-way) transformation from\none type to another.\n\nThis is very powerful, but it can also have unexpected consequences, so you have to explicitly\nask for an attribute to be coerced. To do this, you must set the \"coerce\" attribute option to a\ntrue value.\n\nFirst, we create the subtype to which we will coerce the other types:\n\nsubtype 'My::Types::HTTP::Headers' => as classtype('HTTP::Headers');\n\nWe are creating a subtype rather than using \"HTTP::Headers\" as a type directly. The reason we do\nthis is that coercions are global, and a coercion defined for \"HTTP::Headers\" in our \"Request\"\nclass would then be defined for *all* Moose-using classes in the current Perl interpreter. It's\na best practice to avoid this sort of namespace pollution.\n\nThe \"classtype\" sugar function is simply a shortcut for this:\n\nsubtype 'HTTP::Headers'\n=> as 'Object'\n=> where { $->isa('HTTP::Headers') };\n\nInternally, Moose creates a type constraint for each Moose-using class, but for non-Moose\nclasses, the type must be declared explicitly.\n\nWe could go ahead and use this new type directly:\n\nhas 'headers' => (\nis      => 'rw',\nisa     => 'My::Types::HTTP::Headers',\ndefault => sub { HTTP::Headers->new }\n);\n\nThis creates a simple attribute which defaults to an empty instance of HTTP::Headers.\n\nThe constructor for HTTP::Headers accepts a list of key-value pairs representing the HTTP header\nfields. In Perl, such a list could be stored in an ARRAY or HASH reference. We want our\n\"headers\" attribute to accept those data structures instead of an HTTP::Headers instance, and\njust do the right thing. This is exactly what coercion is for:\n\ncoerce 'My::Types::HTTP::Headers'\n=> from 'ArrayRef'\n=> via { HTTP::Headers->new( @{$} ) }\n=> from 'HashRef'\n=> via { HTTP::Headers->new( %{$} ) };\n\nThe first argument to \"coerce\" is the type *to* which we are coercing. Then we give it a set of\n\"from\"/\"via\" clauses. The \"from\" function takes some other type name and \"via\" takes a\nsubroutine reference which actually does the coercion.\n\nHowever, defining the coercion doesn't do anything until we tell Moose we want a particular\nattribute to be coerced:\n\nhas 'headers' => (\nis      => 'rw',\nisa     => 'My::Types::HTTP::Headers',\ncoerce  => 1,\ndefault => sub { HTTP::Headers->new }\n);\n\nNow, if we use an \"ArrayRef\" or \"HashRef\" to populate \"headers\", it will be coerced into a new\nHTTP::Headers instance. With the coercion in place, the following lines of code are all\nequivalent:\n\n$foo->headers( HTTP::Headers->new( bar => 1, baz => 2 ) );\n$foo->headers( [ 'bar', 1, 'baz', 2 ] );\n$foo->headers( { bar => 1, baz => 2 } );\n\nAs you can see, careful use of coercions can produce a very open interface for your class, while\nstill retaining the \"safety\" of your type constraint checks. (1)\n\nOur next coercion shows how we can leverage existing CPAN modules to help implement coercions.\nIn this case we use Params::Coerce.\n\nOnce again, we need to declare a class type for our non-Moose URI class:\n\nsubtype 'My::Types::URI' => as classtype('URI');\n\nThen we define the coercion:\n\ncoerce 'My::Types::URI'\n=> from 'Object'\n=> via { $->isa('URI')\n? $\n: Params::Coerce::coerce( 'URI', $ ); }\n=> from 'Str'\n=> via { URI->new( $, 'http' ) };\n\nThe first coercion takes any object and makes it a \"URI\" object. The coercion system isn't that\nsmart, and does not check if the object is already a URI, so we check for that ourselves. If\nit's not a URI already, we let Params::Coerce do its magic, and we just use its return value.\n\nIf Params::Coerce didn't return a URI object (for whatever reason), Moose would throw a type\nconstraint error.\n\nThe other coercion takes a string and converts it to a URI. In this case, we are using the\ncoercion to apply a default behavior, where a string is assumed to be an \"http\" URI.\n\nFinally, we need to make sure our attributes enable coercion.\n\nhas 'base' => ( is => 'rw', isa => 'My::Types::URI', coerce => 1 );\nhas 'uri'  => ( is => 'rw', isa => 'My::Types::URI', coerce => 1 );\n\nRe-using the coercion lets us enforce a consistent API across multiple attributes.\n",
            "subsections": []
        },
        "CONCLUSION": {
            "content": "This recipe showed the use of coercions to create a more flexible and DWIM-y API. Like any\npowerful feature, we recommend some caution. Sometimes it's better to reject a value than just\nguess at how to DWIM.\n\nWe also showed the use of the \"classtype\" sugar function as a shortcut for defining a new\nsubtype of \"Object\".\n",
            "subsections": []
        },
        "FOOTNOTES": {
            "content": "(1) This particular example could be safer. Really we only want to coerce an array with an\n*even* number of elements. We could create a new \"EvenElementArrayRef\" type, and then coerce\nfrom that type, as opposed to a plain \"ArrayRef\"\n",
            "subsections": []
        },
        "AUTHORS": {
            "content": "*   Stevan Little <stevan@cpan.org>\n\n*   Dave Rolsky <autarch@urth.org>\n\n*   Jesse Luehrs <doy@cpan.org>\n\n*   Shawn M Moore <sartak@cpan.org>\n\n*   יובל קוג'מן (Yuval Kogman) <nothingmuch@woobling.org>\n\n*   Karen Etheridge <ether@cpan.org>\n\n*   Florian Ragwitz <rafl@debian.org>\n\n*   Hans Dieter Pearcey <hdp@cpan.org>\n\n*   Chris Prather <chris@prather.org>\n\n*   Matt S Trout <mstrout@cpan.org>\n",
            "subsections": []
        },
        "COPYRIGHT AND LICENSE": {
            "content": "This software is copyright (c) 2006 by Infinity Interactive, Inc.\n\nThis is free software; you can redistribute it and/or modify it under the same terms as the Perl\n5 programming language system itself.\n",
            "subsections": []
        }
    },
    "summary": "Moose::Cookbook::Basics::HTTPSubtypesAndCoercion - Demonstrates subtypes and coercion use HTTP-related classes (Request, Protocol, etc.)",
    "flags": [],
    "examples": [],
    "see_also": []
}