in reply to Re: Role::Tiny: When to use apply_roles_to_object?
in thread Role::Tiny: When to use apply_roles_to_object?

> In this particular example, there's an argument for making more use of delegation instead of composition

actually I also had rather delegation in mind when answering this question.

As far as I understood does Role::Tiny -> apply_roles_to_object() actually create a new anonymous package and is reblessing the object. °

IMHO delegation sounds like a better approach, unless the performance penalty of the extra forwarding sub matters.

Cheers Rolf
(addicted to the Perl Programming Language :)
Wikisyntax for the Monastery FootballPerl is like chess, only without the dice

°) quote "Object is reblessed into the resulting class."

  • Comment on Re^2: Role::Tiny: When to use apply_roles_to_object?

Replies are listed 'Best First'.
Re^3: Role::Tiny: When to use apply_roles_to_object?
by tobyink (Canon) on May 04, 2019 at 07:39 UTC

    That's how it works, but should be considered an internal implementation detail.

    Delegation is probably a better approach for the example I used earlier, but it requires the base class to have prior knowledge of the kinds of "plugin functionality" that will be added to it, so that it knows when to delegate to them. In many cases, the base class won't have prior knowledge.

      > but it requires the base class to have prior knowledge of the kinds of "plugin functionality" that will be added to it, so that it knows when to delegate to them.

      Hmm, ... in theory it should be possible to combine roles and delegation.

      Such that the role plugs in the delegations and apply_roles_to_object is blessing the object into the new singleton class.

      Will try it out next week.

      Cheers Rolf
      (addicted to the Perl Programming Language :)
      Wikisyntax for the Monastery FootballPerl is like chess, only without the dice

Re^3: Role::Tiny: When to use apply_roles_to_object?
by 1nickt (Canon) on May 03, 2019 at 18:42 UTC

    "does Role::Tiny -> apply_roles_to_object() actually create a new anonymous package and is reblessing the object"

    That's a feature.

    use strict; use warnings; use feature 'say'; use Role::Tiny; package MyClass { use Moo }; package MyRole { use Moo::Role }; my $o = MyClass->new; Role::Tiny->apply_roles_to_object($o, 'MyRole'); say ref($o);
    Output:
    MyClass__WITH__MyRole


    The way forward always starts with a minimal test.