{
    "mode": "perldoc",
    "parameter": "Moose::Manual::Roles",
    "section": "",
    "url": "https://www.chedong.com/phpMan.php/perldoc/Moose%3A%3AManual%3A%3ARoles/json",
    "generated": "2026-06-12T19:02:08Z",
    "sections": {
        "NAME": {
            "content": "Moose::Manual::Roles - Roles, an alternative to deep hierarchies and base classes\n",
            "subsections": []
        },
        "VERSION": {
            "content": "version 2.2200\n\nWHAT IS A ROLE?\nA role encapsulates some piece of behavior or state that can be shared between classes. It is\nsomething that classes *do*. It is important to understand that *roles are not classes*. You\ncannot inherit from a role, and a role cannot be instantiated. We sometimes say that roles are\n*consumed*, either by classes or other roles.\n\nInstead, a role is *composed* into a class. In practical terms, this means that all of the\nmethods, method modifiers, and attributes defined in a role are added directly to (we sometimes\nsay \"flattened into\") the class that consumes the role. These attributes and methods then appear\nas if they were defined in the class itself. A subclass of the consuming class will inherit all\nof these methods and attributes.\n\nMoose roles are similar to mixins or interfaces in other languages and are based on the original\nconcept of Traits <http://scg.unibe.ch/research/traits/> for the Smalltalk-80 dialect Squeak.\n\nBesides defining their own methods and attributes, roles can also require that the consuming\nclass define certain methods of its own. You could have a role that consisted only of a list of\nrequired methods, in which case the role would be very much like a Java interface.\n\nNote that attribute accessors also count as methods for the purposes of satisfying the\nrequirements of a role.\n",
            "subsections": []
        },
        "A SIMPLE ROLE": {
            "content": "Creating a role looks a lot like creating a Moose class:\n\npackage Breakable;\n\nuse Moose::Role;\n\nhas 'isbroken' => (\nis  => 'rw',\nisa => 'Bool',\n);\n\nsub break {\nmy $self = shift;\n\nprint \"I broke\\n\";\n\n$self->isbroken(1);\n}\n\nExcept for our use of Moose::Role, this looks just like a class definition with Moose. However,\nthis is not a class, and it cannot be instantiated.\n\nInstead, its attributes and methods will be composed into classes which use the role:\n\npackage Car;\n\nuse Moose;\n\nwith 'Breakable';\n\nhas 'engine' => (\nis  => 'ro',\nisa => 'Engine',\n);\n\nThe \"with\" function composes roles into a class. Once that is done, the \"Car\" class has an\n\"isbroken\" attribute and a \"break\" method. The \"Car\" class also \"does('Breakable')\":\n\nmy $car = Car->new( engine => Engine->new );\n\nprint $car->isbroken ? 'Busted' : 'Still working';\n$car->break;\nprint $car->isbroken ? 'Busted' : 'Still working';\n\n$car->does('Breakable'); # true\n\nThis prints:\n\nStill working\nI broke\nBusted\n\nWe could use this same role in a \"Bone\" class:\n\npackage Bone;\n\nuse Moose;\n\nwith 'Breakable';\n\nhas 'marrow' => (\nis  => 'ro',\nisa => 'Marrow',\n);\n\nSee also Moose::Cookbook::Roles::ComparableCodeReuse for an example.\n\nIt's possible to compose existing roles into new roles. For example, we can have a\n\"HandleWithCare\" class which applies both the \"Breakable\" and \"Package\" roles to any class which\nconsumes it:\n\npackage HandleWithCare;\n\nuse Moose::Role;\n\nwith 'Breakable', 'Package';\n",
            "subsections": []
        },
        "REQUIRED METHODS": {
            "content": "As mentioned previously, a role can require that consuming classes provide one or more methods.\nUsing our \"Breakable\" example, let's make it require that consuming classes implement their own\n\"break\" methods:\n\npackage Breakable;\n\nuse Moose::Role;\n\nrequires 'break';\n\nhas 'isbroken' => (\nis  => 'rw',\nisa => 'Bool',\n);\n\nafter 'break' => sub {\nmy $self = shift;\n\n$self->isbroken(1);\n};\n\nIf we try to consume this role in a class that does not have a \"break\" method, we will get an\nexception.\n\nYou can see that we added a method modifier on \"break\". We want classes that consume this role\nto implement their own logic for breaking, but we make sure that the \"isbroken\" attribute is\nalways set to true when \"break\" is called.\n\npackage Car\n\nuse Moose;\n\nwith 'Breakable';\n\nhas 'engine' => (\nis  => 'ro',\nisa => 'Engine',\n);\n\nsub break {\nmy $self = shift;\n\nif ( $self->ismoving ) {\n$self->stop;\n}\n}\n",
            "subsections": [
                {
                    "name": "Roles Versus Abstract Base Classes",
                    "content": "If you are familiar with the concept of abstract base classes in other languages, you may be\ntempted to use roles in the same way.\n\nYou *can* define an \"interface-only\" role, one that contains *just* a list of required methods.\n\nHowever, any class which consumes this role must implement all of the required methods, either\ndirectly or through inheritance from a parent. You cannot delay the method requirement check so\nthat they can be implemented by future subclasses.\n\nBecause the role defines the required methods directly, adding a base class to the mix would not\nachieve anything. We recommend that you simply consume the interface role in each class which\nimplements that interface.\n"
                }
            ]
        },
        "CONSUMING ROLES": {
            "content": "Roles are consumed using the \"with\" function.\n\nMost of the time, you should only use one \"with\", even if you are consuming multiple roles. If\nyou consume roles using multiple \"with\" statements Moose cannot detect method conflicts between\nthose roles.\n\nRoles can be consumed by classes or by other roles. When a class consumes a role which in turn\nconsumes other roles, the class gets all of the roles applied at once.\n",
            "subsections": [
                {
                    "name": "Required Methods Provided by Attributes",
                    "content": "As mentioned before, a role's required method may also be satisfied by an attribute accessor.\nHowever, the call to \"has\" which defines an attribute happens at runtime. This means that you\nmust define the attribute *before* consuming the role, or else the role will not see the\ngenerated accessor. These attributes are Moose Attributes.\n\npackage Breakable;\n\nuse Moose::Role;\n\nrequires 'stress';\n\n########\n\npackage Car;\n\nuse Moose;\n\nhas 'stress' => (\nis  => 'ro',\nisa => 'Int',\n);\n\nwith 'Breakable';\n\nIn general, we recommend that you always consume roles *after* declaring all your attributes.\n\nIt may also be the case that a class wants to consume two roles where one role has an attribute\nproviding a required method for another. For example:\n\npackage Breakable;\n\nuse Moose::Role;\n\nrequires 'stress';\n\n########\n\npackage Stressable;\n\nuse Moose::Role;\n\nhas 'stress' => (\nis  => 'ro',\nisa => 'Int',\n);\n\n########\n\npackage Car;\n\nuse Moose;\n\n# XXX - this will not work\nwith 'Breakable', 'Stressable';\n\nHowever, this won't work. The problem is that the accessor methods created for the \"stress\"\nattribute won't be present in the class when the required method checks are done.\n\nThere are two possible workarounds. The recommended one is to use \"stub\" subroutine(s) in the\nrole providing the accessor(s):\n\npackage Stressable;\n\nuse Moose::Role;\n\nsub stress;\nhas 'stress' => (\nis  => 'ro',\nisa => 'Int',\n);\n\nThe \"sub stress;\" line is called a \"forward\" declaration in the Perl documentation. It creates\nwhat is called a \"stub\" subroutine, a declaration without a body. This is good enough to satisfy\nthe required method checks done by Moose. The stub will not interfere with the creation of a\nreal subroutine later.\n\nThe other alternative is to use two separate calls to \"with\" in the consuming class:\n\npackage Car;\n\nuse Moose;\n\n# Not recommended\nwith 'Stressable';\nwith 'Breakable';\n\nEach \"with\" is run as it is seen. The first call will consume just the \"Stressable\" role, which\nwill add the \"stress\" attribute to the \"Car\" package, which in turn will create an accessor\nmethod named \"stress\". Then when the \"Breakable\" role is consumed, the method it requires\nalready exists.\n\nHowever, as mentioned earlier, multiple \"with\" declarations are not recommended, because method\nconflicts between the roles cannot be seen. In the example above, if both \"Stressable\" and\n\"Breakable\" contained methods of the same name, what would happen is that the version in\n\"Stressable\" would *silently* override the one in \"Breakable\".\n"
                }
            ]
        },
        "USING METHOD MODIFIERS": {
            "content": "Method modifiers and roles are a very powerful combination. Often, a role will combine method\nmodifiers and required methods. We already saw one example with our \"Breakable\" example.\n\nMethod modifiers increase the complexity of roles, because they make the role application order\nrelevant. If a class uses multiple roles, each of which modify the same method, those modifiers\nwill be applied in the same order as the roles are used:\n\npackage MovieCar;\n\nuse Moose;\n\nextends 'Car';\n\nwith 'Breakable', 'ExplodesOnBreakage';\n\nAssuming that the new \"ExplodesOnBreakage\" role *also* has an \"after\" modifier on \"break\", the\n\"after\" modifiers will run one after the other. The modifier from \"Breakable\" will run first,\nthen the one from \"ExplodesOnBreakage\".\n",
            "subsections": []
        },
        "METHOD CONFLICTS": {
            "content": "If a class composes multiple roles, and those roles have methods of the same name, we will have\na conflict. In that case, the composing class is required to provide its *own* method of the\nsame name.\n\npackage Breakdancer;\n\nuse Moose::Role;\n\nsub break {\n\n}\n\nIf we compose both \"Breakable\" and \"Breakdancer\" in a class, we must provide our own \"break\"\nmethod:\n\npackage FragileDancer;\n\nuse Moose;\n\nwith 'Breakable', 'Breakdancer';\n\nsub break { ... }\n\nA role can be a collection of other roles:\n\npackage Break::Bundle;\n\nuse Moose::Role;\n\nwith ('Breakable', 'Breakdancer');\n\nWhen a role consumes another a role, the *consuming* role's methods silently win in any\nconflict, and the consumed role's methods are simply ignored.\n",
            "subsections": []
        },
        "METHOD EXCLUSION AND ALIASING": {
            "content": "If we want our \"FragileDancer\" class to be able to call the methods from both its roles, we can\nalias the methods:\n\npackage FragileDancer;\n\nuse Moose;\n\nwith 'Breakable'   => { -alias => { break => 'breakbone' } },\n'Breakdancer' => { -alias => { break => 'breakdance' } };\n\nHowever, aliasing a method simply makes a *copy* of the method with the new name. We also need\nto exclude the original name:\n\nwith 'Breakable' => {\n-alias    => { break => 'breakbone' },\n-excludes => 'break',\n},\n'Breakdancer' => {\n-alias    => { break => 'breakdance' },\n-excludes => 'break',\n};\n\nThe excludes parameter prevents the \"break\" method from being composed into the \"FragileDancer\"\nclass, so we don't have a conflict. This means that \"FragileDancer\" does not need to implement\nits own \"break\" method.\n\nThis is useful, but it's worth noting that this breaks the contract implicit in consuming a\nrole. Our \"FragileDancer\" class does both the \"Breakable\" and \"BreakDancer\", but does not\nprovide a \"break\" method. If some API expects an object that does one of those roles, it\nprobably expects it to implement that method.\n\nIn some use cases we might alias and exclude methods from roles, but then provide a method of\nthe same name in the class itself.\n\nAlso see Moose::Cookbook::Roles::RestartableAdvancedComposition for an example.\n",
            "subsections": []
        },
        "OVERLOADING": {
            "content": "When a Moose role uses overloading, that overloading is composed into any classes that consume\nthe role. This includes the setting of the \"fallback\" value for that role's overloading. Just as\nwith methods and attributes, when a role consumes another role, that other role's overloading\nsettings are applied to the role.\n\nJust as with methods, there can be conflicts with overloading implementations between multiple\nroles when they are all consumed by a class. If two roles both provide different overloading\nimplementations for a given operator, that is a conflict. If two roles both implement\noverloading and have different \"fallback\" values, that is also considered a conflict. These\nconflicts are detected when multiple roles are being composed into a class together.\n\nWhen a role consumes another role, the consuming role's overloading fallback and operator\nimplementations silently \"win\" the conflict.\n",
            "subsections": []
        },
        "ROLE EXCLUSION": {
            "content": "A role can say that it cannot be combined with some other role. This should be used with great\ncaution, since it limits the re-usability of the role.\n\npackage Breakable;\n\nuse Moose::Role;\n\nexcludes 'BreakDancer';\n",
            "subsections": []
        },
        "ADDING A ROLE TO AN OBJECT INSTANCE": {
            "content": "You may want to add a role to an object instance, rather than to a class. For example, you may\nwant to add debug tracing to one instance of an object while debugging a particular bug. Another\nuse case might be to dynamically change objects based on a user's configuration, as a plugin\nsystem.\n\nThe best way to do this is to use the \"applyallroles()\" function from Moose::Util:\n\nuse Moose::Util qw( applyallroles );\n\nmy $car = Car->new;\napplyallroles( $car, 'Breakable' );\n\nThis function can apply more than one role at a time, and will do so using the normal Moose role\ncombination system. We recommend using this function to apply roles to an object. This is what\nMoose uses internally when you call \"with\".\n",
            "subsections": [
                {
                    "name": "Handling required attributes for roles.",
                    "content": "Application of some roles will require additional parameters being specified to satisfy them,\nfor example:\n\n{\npackage Car;\nuse Moose;\n}\n{\npackage Breakable;\nuse Moose::Role;\n\nhas 'breakableparts' => ( is => 'ro', required => 1 );\n}\n\nmy $car = Car->new;\n\n# next line dies with: Attribute (breakableparts) is required\napplyallroles( $car, 'Breakable' );\n\nThis will require passing the additional parameters at application time as follows:\n\napplyallroles( $car, 'Breakable' => {\nreblessparams => {\n# Parameters to 'Breakable'\nbreakableparts => [qw( tires wheels windscreen )],\n}\n});\n\nObviously, this interface is better simplified as a method on \"Car\":\n\nsub makebreakable {\nmy ( $self, %params ) = @;\napplyallroles($self, 'Breakable', { reblessparams => \\%params });\n}\n\nmy $car = Car->new();\n$car->makebreakable( breakableparts => [qw( tires wheels windscreen )] );\n"
                }
            ]
        },
        "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::Manual::Roles - Roles, an alternative to deep hierarchies and base classes",
    "flags": [],
    "examples": [],
    "see_also": []
}