{
    "mode": "perldoc",
    "parameter": "Moose::Cookbook::Extending::ExtensionOverview",
    "section": "",
    "url": "https://www.chedong.com/phpMan.php/perldoc/Moose%3A%3ACookbook%3A%3AExtending%3A%3AExtensionOverview/json",
    "generated": "2026-11-20T12:37:28Z",
    "sections": {
        "NAME": {
            "content": "Moose::Cookbook::Extending::ExtensionOverview - Moose extension overview\n",
            "subsections": []
        },
        "VERSION": {
            "content": "version 2.2207\n",
            "subsections": []
        },
        "DESCRIPTION": {
            "content": "Moose provides several ways in which extensions can hook into Moose and change its behavior.\nMoose also has a lot of behavior that can be changed. This recipe will provide an overview of\neach extension method and give you some recommendations on what tools to use.\n\nIf you haven't yet read the recipes on metaclasses, go read those first. You can't write Moose\nextensions without understanding the metaclasses, and those recipes also demonstrate some basic\nextension mechanisms, such as metaclass subclasses and traits.\n",
            "subsections": [
                {
                    "name": "Playing Nice With Others",
                    "content": "One of the goals of this overview is to help you build extensions that cooperate well with other\nextensions. This is especially important if you plan to release your extension to CPAN.\n\nMoose comes with several modules that exist to help your write cooperative extensions. These are\nMoose::Exporter and Moose::Util::MetaRole. By using these two modules, you will ensure that your\nextension works with both the Moose core features and any other CPAN extension using those\nmodules.\n\nPARTS OF Moose YOU CAN EXTEND\nThe types of things you might want to do in Moose extensions fall into a few broad categories.\n"
                },
                {
                    "name": "Metaclass Extensions",
                    "content": "One way of extending Moose is by extending one or more Moose metaclasses. For example, in\nMoose::Cookbook::Meta::TableMetaclassTrait we saw a metaclass role that added a \"table\"\nattribute to the metaclass. If you were writing an ORM, this would be a logical extension.\n\nMany of the Moose extensions on CPAN work by providing an attribute metaclass role. For example,\nthe MooseX::Aliases module provides an attribute metaclass trait that lets you specify aliases\nto install for methods and attribute accessors.\n\nA metaclass extension can be packaged as a role/trait or a subclass. If you can, we recommend\nusing traits instead of subclasses, since it's much easier to combine disparate traits than it\nis to combine a bunch of subclasses.\n\nWhen your extensions are implemented as roles, you can apply them with the Moose::Util::MetaRole\nmodule.\n"
                },
                {
                    "name": "Providing Sugar Functions",
                    "content": "As part of a metaclass extension, you may also want to provide some sugar functions, just like\nMoose.pm does. Moose provides a helper module called Moose::Exporter that makes this much\nsimpler. We will be use Moose::Exporter in several of the extension recipes.\n"
                },
                {
                    "name": "Object Class Extensions",
                    "content": "Another common Moose extension technique is to change the default object class's behavior. As\nwith metaclass extensions, this can be done with a role/trait or with a subclass. For example,\nMooseX::StrictConstructor extension applies a trait that makes the constructor reject arguments\nwhich don't match its attributes.\n\nObject class extensions often include metaclass extensions as well. In particular, if you want\nyour object extension to work when a class is made immutable, you may need to modify the\nbehavior of some or all of the Moose::Meta::Instance, Moose::Meta::Method::Constructor, and\nMoose::Meta::Method::Destructor objects.\n\nThe Moose::Util::MetaRole module lets you apply roles to the base object class, as well as the\nmeta classes just mentioned.\n"
                },
                {
                    "name": "Providing a Role",
                    "content": "Some extensions come in the form of a role for you to consume. The MooseX::Object::Pluggable\nextension is a great example of this. In fact, despite the \"MooseX\" name, it does not actually\nchange anything about Moose's behavior. Instead, it is just a role that an object which wants to\nbe pluggable can consume.\n\nIf you are implementing this sort of extension, you don't need to do anything special. You\nsimply create a role and document that it should be used via the normal \"with\" sugar:\n\npackage MyApp::User;\n\nuse Moose;\n\nwith 'My::Role';\n\nDon't use \"MooseX\" in the name for such packages.\n"
                },
                {
                    "name": "New Types",
                    "content": "Another common Moose extension is a new type for the Moose type system. In this case, you simply\ncreate a type in your module. When people load your module, the type is created, and they can\nrefer to it by name after that. The MooseX::Types::URI and MooseX::Types::DateTime distributions\nare two good examples of how this works. These both build on top of the MooseX::Types extension.\n"
                }
            ]
        },
        "ROLES VS TRAITS VS SUBCLASSES": {
            "content": "It is important to understand that roles and traits are the same thing. A trait is simply a role\napplied to a instance. The only thing that may distinguish the two is that a trait can be\npackaged in a way that lets Moose resolve a short name to a class name. In other words, with a\ntrait, the caller can refer to it by a short name like \"Big\", and Moose will resolve it to a\nclass like \"MooseX::Embiggen::Meta::Attribute::Role::Big\".\n\nSee Moose::Cookbook::Meta::LabeledAttributeTrait and\nMoose::Cookbook::Meta::TableMetaclassTrait for examples of traits in action. In particular,\nboth of these recipes demonstrate the trait resolution mechanism.\n\nImplementing an extension as a (set of) metaclass or base object role(s) will make your\nextension more cooperative. It is hard for an end-user to effectively combine together multiple\nmetaclass subclasses, but it is very easy to combine roles.\n",
            "subsections": []
        },
        "USING YOUR EXTENSION": {
            "content": "There are a number of ways in which an extension can be applied. In some cases you can provide\nmultiple ways of consuming your extension.\n",
            "subsections": [
                {
                    "name": "Extensions as Metaclass Traits",
                    "content": "If your extension is available as a trait, you can ask end users to simply specify it in a list\nof traits. Currently, this only works for (class) metaclass and attribute metaclass traits:\n\nuse Moose -traits => [ 'Big', 'Blue' ];\n\nhas 'animal' => (\ntraits => [ 'Big', 'Blue' ],\n...\n);\n\nIf your extension applies to any other metaclass, or the object base class, you cannot use the\ntrait mechanism.\n\nThe benefit of the trait mechanism is that is very easy to see where a trait is applied in the\ncode, and consumers have fine-grained control over what the trait applies to. This is especially\ntrue for attribute traits, where you can apply the trait to just one attribute in a class.\n\nExtensions as Metaclass (and Base Object) Roles\nImplementing your extensions as metaclass roles makes your extensions easy to apply, and\ncooperative with other role-based extensions for metaclasses.\n\nJust as with a subclass, you will probably want to package your extensions for consumption with\na single module that uses Moose::Exporter. However, in this case, you will use\nMoose::Util::MetaRole to apply all of your roles. The advantage of using this module is that *it\npreserves any subclassing or roles already applied to the user's metaclasses*. This means that\nyour extension is cooperative *by default*, and consumers of your extension can easily use it\nwith other role-based extensions. Most uses of Moose::Util::MetaRole can be handled by\nMoose::Exporter directly; see the Moose::Exporter docs.\n\npackage MooseX::Embiggen;\n\nuse Moose::Exporter;\n\nuse MooseX::Embiggen::Role::Meta::Class;\nuse MooseX::Embiggen::Role::Meta::Attribute;\nuse MooseX::Embiggen::Role::Meta::Method::Constructor;\nuse MooseX::Embiggen::Role::Object;\n\nMoose::Exporter->setupimportmethods(\nclassmetaroles => {\nclass     => ['MooseX::Embiggen::Role::Meta::Class'],\nattribute => ['MooseX::Embiggen::Role::Meta::Attribute'],\nconstructor =>\n['MooseX::Embiggen::Role::Meta::Method::Constructor'],\n},\nbaseclassroles => ['MooseX::Embiggen::Role::Object'],\n);\n\nAs you can see from this example, you can use Moose::Util::MetaRole to apply roles to any\nmetaclass, as well as the base object class. If some other extension has already applied its own\nroles, they will be preserved when your extension applies its roles, and vice versa.\n"
                },
                {
                    "name": "Providing Sugar",
                    "content": "With Moose::Exporter, you can also export your own sugar functions:\n\npackage MooseX::Embiggen;\n\nuse Moose::Exporter;\n\nMoose::Exporter->setupimportmethods(\nwithmeta       => ['embiggen'],\nclassmetaroles => {\nclass => ['MooseX::Embiggen::Role::Meta::Class'],\n},\n);\n\nsub embiggen {\nmy $meta = shift;\n$meta->embiggen(@);\n}\n\nAnd then the consumer of your extension can use your \"embiggen\" sub:\n\npackage Consumer;\n\nuse Moose;\nuse MooseX::Embiggen;\n\nextends 'Thing';\n\nembiggen ...;\n\nThis can be combined with metaclass and base class roles quite easily.\n"
                },
                {
                    "name": "More advanced extensions",
                    "content": "Providing your extension simply as a set of traits that gets applied to the appropriate\nmetaobjects is easy, but sometimes not sufficient. For instance, sometimes you need to supply\nnot just a base object role, but an actual base object class (due to needing to interact with\nexisting systems that only provide a base class). To write extensions like this, you will need\nto provide a custom \"initmeta\" method in your exporter. For instance:\n\npackage MooseX::Embiggen;\n\nuse Moose::Exporter;\n\nmy ($import, $unimport, $initmeta) = Moose::Exporter->buildimportmethods(\ninstall         => ['import', 'unimport'],\nwithmeta       => ['embiggen'],\nclassmetaroles => {\nclass => ['MooseX::Embiggen::Role::Meta::Class'],\n},\n);\n\nsub embiggen {\nmy $meta = shift;\n$meta->embiggen(@);\n}\n\nsub initmeta {\nmy $package = shift;\nmy %options = @;\nif (my $meta = Class::MOP::classof($options{forclass})) {\nif ($meta->isa('Class::MOP::Class')) {\nmy @supers = $meta->superclasses;\n$meta->superclasses('MooseX::Embiggen::Base::Class')\nif @supers == 1 && $supers[0] eq 'Moose::Object';\n}\n}\n$package->$initmeta(%options);\n}\n\nIn the previous examples, \"initmeta\" was generated for you, but here you must override it in\norder to add additional functionality. Some differences to note:\n\n\"buildimportmethods\" instead of \"setupimportmethods\"\n\"buildimportmethods\" simply returns the \"import\", \"unimport\", and \"initmeta\" methods,\nrather than installing them under the appropriate names. This way, you can write your own\nmethods which wrap the functionality provided by Moose::Exporter. The \"buildimportmethods\"\nsub also takes an additional \"install\" parameter, which tells it to just go ahead and\ninstall these methods (since we don't need to modify them).\n\n\"sub initmeta\"\nNext, we must write our \"initmeta\" wrapper. The important things to remember are that it is\ncalled as a method, and that %options needs to be passed through to the existing\nimplementation. We call the base implementation by using the $initmeta subroutine reference\nthat was returned by \"buildimportmethods\" earlier.\n\nAdditional implementation\nThis extension sets a different default base object class. To do so, it first checks to see\nif it's being applied to a class, and then checks to see if Moose::Object is that class's\nonly superclass, and if so, replaces that with the superclass that this extension requires.\n\nNote that two extensions that do this same thing will not work together properly (the second\nextension to be loaded won't see Moose::Object as the base object, since it has already been\noverridden). This is why using a base object role is recommended for the general case.\n\nThis \"initmeta\" also works defensively, by only applying its functionality if a metaclass\nalready exists. This makes sure it doesn't break with legacy extensions which override the\nmetaclass directly (and so must be the first extension to initialize the metaclass). This is\nlikely not necessary, since almost no extensions work this way anymore, but just provides an\nadditional level of protection. The common case of \"use Moose; use MooseX::Embiggen;\" is not\naffected regardless.\n\nThis is just one example of what can be done with a custom \"initmeta\" method. It can also be\nused for preventing an extension from being applied to a role, doing other kinds of validation\non the class being applied to, or pretty much anything that would otherwise be done in an\n\"import\" method.\n"
                }
            ]
        },
        "LEGACY EXTENSION MECHANISMS": {
            "content": "Before the existence of Moose::Exporter and Moose::Util::MetaRole, there were a number of other\nways to extend Moose. In general, these methods were less cooperative, and only worked well with\na single extension.\n\nThese methods include metaclass.pm, Moose::Policy (which uses metaclass.pm under the hood), and\nvarious hacks to do what Moose::Exporter does. Please do not use these for your own extensions.\n\nNote that if you write a cooperative extension, it should cooperate with older extensions,\nthough older extensions generally do not cooperate with each other.\n",
            "subsections": []
        },
        "CONCLUSION": {
            "content": "If you can write your extension as one or more metaclass and base object roles, please consider\ndoing so. Make sure to read the docs for Moose::Exporter and Moose::Util::MetaRole as well.\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::Extending::ExtensionOverview - Moose extension overview",
    "flags": [],
    "examples": [],
    "see_also": []
}