UR::Role(3pm)

πŸ“¦
version 0.470 Β· 2 versions
, in debian bookworm, ubuntu jammy, ubuntu noble

πŸŽ€ 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 has section 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 to undef, it is compatible with other values.
  • A Role that sets its 'fallback' value to true or false is only compatible with other roles' values of undef or 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 $rv will 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 🌟

  • UR
  • UR::Object::Type::Initializer
  • UR::Role::Instance
  • UR::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