{
    "content": [
        {
            "type": "text",
            "text": "# Moose::Manual::Roles (info)\n\n## NAME\n\nMoose::Manual::Roles - Roles, an alternative to deep hierarchies and base classes\n\n## Sections\n\n- **Moose::Manual::Roles(3User Contributed Perl DocumentaMoose::Manual::Roles(3pm)**\n- **NAME**\n- **VERSION**\n- **A SIMPLE ROLE**\n- **REQUIRED METHODS**\n- **CONSUMING ROLES**\n- **USING METHOD MODIFIERS**\n- **METHOD CONFLICTS**\n- **METHOD EXCLUSION AND ALIASING**\n- **OVERLOADING**\n- **ROLE EXCLUSION**\n- **ADDING A ROLE TO AN OBJECT INSTANCE**\n- **AUTHORS**\n- **COPYRIGHT AND LICENSE**\n\nUse structuredContent.sections for detailed options, examples, and full documentation.\n"
        }
    ],
    "structuredContent": {
        "command": "Moose::Manual::Roles",
        "section": "",
        "mode": "info",
        "summary": "Moose::Manual::Roles - Roles, an alternative to deep hierarchies and base classes",
        "synopsis": null,
        "tldr_summary": null,
        "tldr_examples": [],
        "tldr_source": null,
        "flags": [],
        "examples": [],
        "see_also": [],
        "section_outline": [
            {
                "name": "Moose::Manual::Roles(3User Contributed Perl DocumentaMoose::Manual::Roles(3pm)",
                "lines": 1,
                "subsections": []
            },
            {
                "name": "NAME",
                "lines": 3,
                "subsections": []
            },
            {
                "name": "VERSION",
                "lines": 29,
                "subsections": []
            },
            {
                "name": "A SIMPLE ROLE",
                "lines": 80,
                "subsections": []
            },
            {
                "name": "REQUIRED METHODS",
                "lines": 65,
                "subsections": []
            },
            {
                "name": "CONSUMING ROLES",
                "lines": 115,
                "subsections": []
            },
            {
                "name": "USING METHOD MODIFIERS",
                "lines": 22,
                "subsections": []
            },
            {
                "name": "METHOD CONFLICTS",
                "lines": 35,
                "subsections": []
            },
            {
                "name": "METHOD EXCLUSION AND ALIASING",
                "lines": 38,
                "subsections": []
            },
            {
                "name": "OVERLOADING",
                "lines": 17,
                "subsections": []
            },
            {
                "name": "ROLE EXCLUSION",
                "lines": 10,
                "subsections": []
            },
            {
                "name": "ADDING A ROLE TO AN OBJECT INSTANCE",
                "lines": 59,
                "subsections": []
            },
            {
                "name": "AUTHORS",
                "lines": 20,
                "subsections": []
            },
            {
                "name": "COPYRIGHT AND LICENSE",
                "lines": 6,
                "subsections": []
            }
        ],
        "sections": {
            "Moose::Manual::Roles(3User Contributed Perl DocumentaMoose::Manual::Roles(3pm)": {
                "content": "",
                "subsections": []
            },
            "NAME": {
                "content": "Moose::Manual::Roles - Roles, an alternative to deep hierarchies and\nbase 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\nbetween classes. It is something that classes do. It is important to\nunderstand that roles are not classes. You cannot inherit from a role,\nand a role cannot be instantiated. We sometimes say that roles are\nconsumed, either by classes or other roles.\n\nInstead, a role is composed into a class. In practical terms, this\nmeans that all of the methods, method modifiers, and attributes defined\nin a role are added directly to (we sometimes say \"flattened into\") the\nclass that consumes the role. These attributes and methods then appear\nas if they were defined in the class itself. A subclass of the\nconsuming class will inherit all of these methods and attributes.\n\nMoose roles are similar to mixins or interfaces in other languages and\nare based on the original concept of Traits\n<http://scg.unibe.ch/research/traits/> for the Smalltalk-80 dialect\nSqueak.\n\nBesides defining their own methods and attributes, roles can also\nrequire that the consuming class define certain methods of its own. You\ncould have a role that consisted only of a list of required methods, in\nwhich case the role would be very much like a Java interface.\n\nNote that attribute accessors also count as methods for the purposes of\nsatisfying the requirements 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\ndefinition with Moose. However, this is not a class, and it cannot be\ninstantiated.\n\nInstead, its attributes and methods will be composed into classes which\nuse 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\n\"Car\" class has an \"isbroken\" attribute and a \"break\" method. The\n\"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\ncan have a \"HandleWithCare\" class which applies both the \"Breakable\"\nand \"Package\" roles to any class which consumes 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\nprovide one or more methods. Using our \"Breakable\" example, let's make\nit require that consuming classes implement their own \"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\"\nmethod, we will get an exception.\n\nYou can see that we added a method modifier on \"break\". We want classes\nthat consume this role to implement their own logic for breaking, but\nwe make sure that the \"isbroken\" attribute is always set to true when\n\"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\nRoles Versus Abstract Base Classes\nIf you are familiar with the concept of abstract base classes in other\nlanguages, you may be tempted to use roles in the same way.\n\nYou can define an \"interface-only\" role, one that contains just a list\nof required methods.\n\nHowever, any class which consumes this role must implement all of the\nrequired methods, either directly or through inheritance from a parent.\nYou cannot delay the method requirement check so that they can be\nimplemented by future subclasses.\n\nBecause the role defines the required methods directly, adding a base\nclass to the mix would not achieve anything. We recommend that you\nsimply consume the interface role in each class which implements that\ninterface.\n",
                "subsections": []
            },
            "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\nconsuming multiple roles. If you consume roles using multiple \"with\"\nstatements Moose cannot detect method conflicts between those roles.\n\nRoles can be consumed by classes or by other roles. When a class\nconsumes a role which in turn consumes other roles, the class gets all\nof the roles applied at once.\n\nRequired Methods Provided by Attributes\nAs mentioned before, a role's required method may also be satisfied by\nan attribute accessor. However, the call to \"has\" which defines an\nattribute happens at runtime. This means that you must define the\nattribute 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\nall your attributes.\n\nIt may also be the case that a class wants to consume two roles where\none role has an attribute providing a required method for another. For\nexample:\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\ncreated for the \"stress\" attribute won't be present in the class when\nthe required method checks are done.\n\nThere are two possible workarounds. The recommended one is to use\n\"stub\" subroutine(s) in the role 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\ndocumentation. It creates what is called a \"stub\" subroutine, a\ndeclaration without a body. This is good enough to satisfy the required\nmethod checks done by Moose. The stub will not interfere with the\ncreation of a real subroutine later.\n\nThe other alternative is to use two separate calls to \"with\" in the\nconsuming 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\n\"Stressable\" role, which will add the \"stress\" attribute to the \"Car\"\npackage, which in turn will create an accessor method named \"stress\".\nThen when the \"Breakable\" role is consumed, the method it requires\nalready exists.\n\nHowever, as mentioned earlier, multiple \"with\" declarations are not\nrecommended, because method conflicts between the roles cannot be seen.\nIn the example above, if both \"Stressable\" and \"Breakable\" contained\nmethods of the same name, what would happen is that the version in\n\"Stressable\" would silently override the one in \"Breakable\".\n",
                "subsections": []
            },
            "USING METHOD MODIFIERS": {
                "content": "Method modifiers and roles are a very powerful combination.  Often, a\nrole will combine method modifiers and required methods. We already saw\none example with our \"Breakable\" example.\n\nMethod modifiers increase the complexity of roles, because they make\nthe role application order relevant. If a class uses multiple roles,\neach of which modify the same method, those modifiers will be applied\nin 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\"\nmodifier on \"break\", the \"after\" modifiers will run one after the\nother. The modifier from \"Breakable\" will run first, then the one from\n\"ExplodesOnBreakage\".\n",
                "subsections": []
            },
            "METHOD CONFLICTS": {
                "content": "If a class composes multiple roles, and those roles have methods of the\nsame name, we will have a conflict. In that case, the composing class\nis required to provide its own method of the same 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\nprovide our own \"break\" method:\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\nsilently win in any conflict, and the consumed role's methods are\nsimply ignored.\n",
                "subsections": []
            },
            "METHOD EXCLUSION AND ALIASING": {
                "content": "If we want our \"FragileDancer\" class to be able to call the methods\nfrom both its roles, we can alias 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\nnew name. We also need to 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\ninto the \"FragileDancer\" class, so we don't have a conflict. This means\nthat \"FragileDancer\" does not need to implement its own \"break\" method.\n\nThis is useful, but it's worth noting that this breaks the contract\nimplicit in consuming a role. Our \"FragileDancer\" class does both the\n\"Breakable\" and \"BreakDancer\", but does not provide a \"break\" method.\nIf some API expects an object that does one of those roles, it probably\nexpects it to implement that method.\n\nIn some use cases we might alias and exclude methods from roles, but\nthen provide a method of the same name in the class itself.\n\nAlso see Moose::Cookbook::Roles::RestartableAdvancedComposition for an\nexample.\n",
                "subsections": []
            },
            "OVERLOADING": {
                "content": "When a Moose role uses overloading, that overloading is composed into\nany classes that consume the role. This includes the setting of the\n\"fallback\" value for that role's overloading. Just as with methods and\nattributes, when a role consumes another role, that other role's\noverloading settings are applied to the role.\n\nJust as with methods, there can be conflicts with overloading\nimplementations between multiple roles when they are all consumed by a\nclass. If two roles both provide different overloading implementations\nfor a given operator, that is a conflict. If two roles both implement\noverloading and have different \"fallback\" values, that is also\nconsidered a conflict. These conflicts are detected when multiple roles\nare being composed into a class together.\n\nWhen a role consumes another role, the consuming role's overloading\nfallback and operator implementations silently \"win\" the conflict.\n",
                "subsections": []
            },
            "ROLE EXCLUSION": {
                "content": "A role can say that it cannot be combined with some other role. This\nshould be used with great caution, since it limits the re-usability of\nthe 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\nclass. For example, you may want to add debug tracing to one instance\nof an object while debugging a particular bug. Another use case might\nbe to dynamically change objects based on a user's configuration, as a\nplugin system.\n\nThe best way to do this is to use the \"applyallroles()\" function from\nMoose::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\nusing the normal Moose role combination system. We recommend using this\nfunction to apply roles to an object. This is what Moose uses\ninternally when you call \"with\".\n\nHandling required attributes for roles.\nApplication of some roles will require additional parameters being\nspecified to satisfy them, for 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\nas 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",
                "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                      2022-02-06         Moose::Manual::Roles(3pm)",
                "subsections": []
            }
        }
    }
}