UR::Role(3pm)
π NAME π
okay so bestie, welcome to UR::Role (you know, the 3pm one) β it's all about Roles in UR, an alternative to inheritance. π
periodt.
β¨ SYNOPSIS β¨
package My::Role;
role My::Role {
id_by => [
role_id_property => { is => 'String' },
],
has => [
role_property => { is => 'String' },
another_prop => { is => 'Integer' },
],
requires => ['class_method'],
excludes => ['Bad::Role'],
};
sub role_method { ... }
package My::Class;
class My::Class {
has => [
class_property => { is => 'Integer ' },
],
roles => ['My::Role'],
};
sub class_method { ... }
my $obj = My::Class->new();
$obj->does('My::Role'); # true
likeβ¦ look at that. $obj->does('My::Role') coming back true. we love to see it. π«Ά
π DESCRIPTION π
Roles are how you encapsulate a piece of behavior so other classes can justβ¦ have it. They've got properties and methods that get melded into any class that composes them. And a Role can be picky β it can require any composing class to implement a whole list of methods or properties. iconic behavior honestly.
β οΈ big one, don't skip: Roles are not classes. They can not be instantiated, and they can not be inherited from. nope nope nope. π
You compose them into a class by listing their names in the roles attribute of a class definition. that's it, that's the move. β¨
πΈ Defining a Role πΈ
Roles get defined with the role keyword. The definition looks very similar to a class definition, as described over in UR::Object::Type::Initializer. Specifically:
- Roles have a
hassection to define properties, and they accept many class-meta attributes such as'id_generator','valid_signals', and'doc'. - Roles may implement operator overloading via the
'use overload'mechanism.
And then Roles also have their own unique attributes for declaring restrictions on how they get used:
requiresβ a listref of property and method names that must appear in any class composing the Role. ngl this one's flexible though: properties and methods defined in other roles or parent classes can totally satisfy a requirement. π«excludesβ a listref of Role names that may not be composed together with this Role. this is the one you use to declare incompatibilities between roles. it's giving "we don't vibe, don't put us in the same class." π
π¦ Composing a Role π¦
Compose one or more Roles into a class using the 'roles' attribute in a class definition.
class My::Class {
roles => ['My::Role', 'Other::Role'],
is => ['Parent::Class'],
has => ['prop_a','prop_b'],
};
Here's the tea on what actually happens when you do that:
- Properties and meta-attributes from the Roles get copied into the composing class.
- Subroutines defined in the Roles' namespaces get imported into the class's namespace.
- Operator overloads defined in the Roles get applied to the class.
π Property and meta-attribute conflicts
An exception is thrown if multiple Roles are composed together that define the same property β even if the composing class defines the same property in an attempt to override them. like, don't even try it, bestie. π
A class may declare a property with the same name that a role also declares. In that case the definition in the class overrides whatever appears in the role. β
But heads up: an exception is thrown if a role declares an ID property in the 'id_by' section and the consuming class redeclares it in the 'has' section as a normal property. π¨
π§ Method conflicts
An exception is thrown if multiple Roles are composed together that define the same subroutine β or if the composing class (or any of its parent classes) defines the same subroutine as any of the roles. yikes.
So if the class wants to override a subroutine defined in one of its roles, the override must be declared with the "Overrides" attribute:
sub overridden_method : Overrides(My::Role, Other::Role) { ... }
All the conflicting role names must be listed in the override, separated by commas. The class will probably implement whatever behavior is required β maybe by calling one role's method or the other, both methods, neither, or literally anything else. main character energy, do what you want. π
And to call a function in a role, you must use the function's fully qualified name, including the role's package. no shortcuts. π
π Overload conflicts
Same energy as method conflicts: an exception is thrown if multiple Roles are composed together that overload the same operator β unless the composing class also overloads that same operator.
An exception is also thrown if composed roles define incompatible 'fallback' behavior. here's the rule, memorise it:
- If a role does not specify
'fallback', or explicitly sets it toundef, it is compatible with other values. - A Role that sets its
'fallback'value to true or false is only compatible with other roles' values ofundefor the same true or false value.
β __import__ β
Each time a Role is composed into a class, its "__import__()" method is called. "__import__()" gets passed two arguments:
- The name of the role
- The class metadata object composing the role
And this happens after the class is completely constructed. like, class is fully built, and then the vibes get imported. β¨
π Parameterized Roles π
Scalar variables with the "RoleParam" attribute are designated as role params. You can supply values when a role composes the role, as a way to give the role more flexibility and genericity. obsessed. π
package ObjectDisplayer;
use ProjectNamespace;
our $target_type : RoleParam(target_type);
role ObjectDisplayer {
has => [
target_object => { is => $target_type },
],
};
package ShowCars;
class ShowCars {
roles => [ ObjectDisplayer->create(target_type => 'Car' ],
};
When the role is composed, the call to "create()" in the class definition creates a UR::Role::Instance to represent the ObjectDisplayer role being composed into the ShowCars class with the params { target_type =" 'car' }>. Values for the role param values in the role definition are swapped out with the provided values as the role's properties are composed into the class. π
At run-time, these role param variables are tied with the UR::Role::Param class. Its "FETCH" method searches the call stack for the first function whose invocant composes the role where the variable's value is being fetched from. The proper param value is returned. π
β οΈ An exception is thrown if a class composes a role and either provides unknown role params or omits values for existing params. no half-sending the assignment, bestie.
π«Ά Method Modifiers π«Ά
Roles can hook into methods defined in consuming classes by using the "before", "after" and "around" method modifiers. this is where it gets so good.
use UR;
package RoleWithModifiers;
use UR::Role qw(before after around);
role RoleWithModifiers { };
before 'do_something' => sub {
my($self, @params) = @_;
print "Calling do_something with params ",join(',',@params),"\n";
};
after 'do_something' => sub {
my($rv, $self, @params) = @_;
print "Result from do_something: $rv\n";
};
around 'do_something' => sub {
my($orig, $self, @params) = @_;
print "Wrapped call to do_something params ",join(',',@params),"\n";
my $rv = $self->$orig(@params);
print "The wrapped call to do_something returned $rv\n";
return 123;
};
package ClassUsingRole;
class ClassUsingRole { roles => 'RoleWithModifiers' };
sub do_something {
print "In original do_something\n";
return 'abc';
}
my $rv = ClassUsingRole->create()->do_something();
print "The call to do_something returned $rv\n";
Running this code will generate the following output:
Wrapped call to do_something params
Calling do_something with params
In original do_something
Result from do_something: abc
The wrapped call to do_something returned abc
The call to do_something returned 123
Method modifiers are applied in the order they appear in the role's implementation. π
before(@params)β A"before"modifier runs before the named method. It receives all the arguments and"wantarray"context as the original method call. It cannot affect the parameters to the original method call, and its return value is ignored. πafter($rv, @params)β The first argument to an"after"modifier is the return value of the original method call; the remaining arguments and"wantarray"context are the same as the original method call. If the original method was called in list context, then$rvwill be an arrayref containing the list of return values. This modifier's return value is ignored. πaround($orig, @params)β An"around"modifier is run in place of the original method, and receives a coderef of the original method as its first argument. Around modifiers can munge arguments and return values, and control when and whether the original method is called. absolute power move. π
π SEE ALSO π
URUR::Object::Type::InitializerUR::Role::InstanceUR::Role::Param
and that's the whole page, bestie!! ππβ¨ this one's perl v5.32.1, dated 2022-01-17, and it's UR::Role(3pm) β go forth and compose responsibly. slay. π
π¦
π¦ where this page comes from
- debian bookworm: libur-perl 0.470+ds-2 Β· Artistic-1.0-Perl OR GPL-1.0-or-later
- ubuntu jammy: libur-perl 0.470+ds-2 Β· Artistic-1.0-Perl OR GPL-1.0-or-later
- ubuntu noble: libur-perl 0.470+ds-2 Β· Artistic-1.0-Perl OR GPL-1.0-or-later
- π girlified by deepseek-ai/DeepSeek-V4.1-Flash on : a language model's rewrite of the original, under its terms