{
    "mode": "info",
    "parameter": "Moose::Cookbook::Basics::HTTP_SubtypesAndCoercion",
    "section": "",
    "url": "https://www.chedong.com/phpMan.php/info/Moose%3A%3ACookbook%3A%3ABasics%3A%3AHTTP_SubtypesAndCoercion/json",
    "generated": "2026-07-07T03:58:45Z",
    "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": {
        "Moose::Cookbook::BasicUsMoose::Cookbook::Basics::HTTPSubtypesAndCoercion(3pm)": {
            "content": "",
            "subsections": []
        },
        "NAME": {
            "content": "Moose::Cookbook::Basics::HTTPSubtypesAndCoercion - Demonstrates\nsubtypes and coercion use HTTP-related classes (Request, Protocol,\netc.)\n",
            "subsections": []
        },
        "VERSION": {
            "content": "version 2.2200\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\n\"coerce\" sugar function. Coercions are attached to existing type\nconstraints, and define a (one-way) transformation from one type to\nanother.\n\nThis is very powerful, but it can also have unexpected consequences, so\nyou have to explicitly ask for an attribute to be coerced. To do this,\nyou must set the \"coerce\" attribute option to a true 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\ndirectly. The reason we do this is that coercions are global, and a\ncoercion defined for \"HTTP::Headers\" in our \"Request\" class would then\nbe defined for all Moose-using classes in the current Perl interpreter.\nIt's a 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,\nbut for non-Moose classes, 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\nHTTP::Headers.\n\nThe constructor for HTTP::Headers accepts a list of key-value pairs\nrepresenting the HTTP header fields. In Perl, such a list could be\nstored in an ARRAY or HASH reference. We want our \"headers\" attribute\nto accept those data structures instead of an HTTP::Headers instance,\nand just 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.\nThen we give it a set of \"from\"/\"via\" clauses. The \"from\" function\ntakes some other type name and \"via\" takes a subroutine reference which\nactually does the coercion.\n\nHowever, defining the coercion doesn't do anything until we tell Moose\nwe want a particular attribute 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\nwill be coerced into a new HTTP::Headers instance. With the coercion in\nplace, the following lines of code are all equivalent:\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\ninterface for your class, while still retaining the \"safety\" of your\ntype constraint checks. (1)\n\nOur next coercion shows how we can leverage existing CPAN modules to\nhelp implement coercions. In this case we use Params::Coerce.\n\nOnce again, we need to declare a class type for our non-Moose URI\nclass:\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\ncoercion system isn't that smart, and does not check if the object is\nalready a URI, so we check for that ourselves. If it's not a URI\nalready, we let Params::Coerce do its magic, and we just use its return\nvalue.\n\nIf Params::Coerce didn't return a URI object (for whatever reason),\nMoose would throw a type constraint error.\n\nThe other coercion takes a string and converts it to a URI. In this\ncase, we are using the coercion to apply a default behavior, where a\nstring 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\nattributes.\n",
            "subsections": []
        },
        "CONCLUSION": {
            "content": "This recipe showed the use of coercions to create a more flexible and\nDWIM-y API. Like any powerful feature, we recommend some caution.\nSometimes it's better to reject a value than just guess at how to DWIM.\n\nWe also showed the use of the \"classtype\" sugar function as a shortcut\nfor defining a new subtype of \"Object\".\n",
            "subsections": []
        },
        "FOOTNOTES": {
            "content": "(1) This particular example could be safer. Really we only want to\ncoerce an array with an even number of elements. We could create a\nnew \"EvenElementArrayRef\" type, and then coerce from that type, as\nopposed to a plain \"ArrayRef\"\n",
            "subsections": []
        },
        "AUTHORS": {
            "content": "o   Stevan Little <stevan@cpan.org>\n\no   Dave Rolsky <autarch@urth.org>\n\no   Jesse Luehrs <doy@cpan.org>\n\no   Shawn M Moore <sartak@cpan.org>\n\no    ' (Yuval Kogman) <nothingmuch@woobling.org>\n\no   Karen Etheridge <ether@cpan.org>\n\no   Florian Ragwitz <rafl@debian.org>\n\no   Hans Dieter Pearcey <hdp@cpan.org>\n\no   Chris Prather <chris@prather.org>\n\no   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\nthe same terms as the Perl 5 programming language system itself.\n\nperl v5.34.0            Moose::Cookbook::Basics::HTTPSubtypesAndCoercion(3pm)",
            "subsections": []
        }
    },
    "summary": "Moose::Cookbook::Basics::HTTPSubtypesAndCoercion - Demonstrates subtypes and coercion use HTTP-related classes (Request, Protocol, etc.)",
    "flags": [],
    "examples": [],
    "see_also": []
}