Note that there are some explanatory texts on larger screens.

plurals
  1. POHow do Roles and Traits differ in Moose?
    text
    copied!<p>I have written a set of classes and interfaces that are implemented in <a href="http://search.cpan.org/~drolsky/Moose-0.87/lib/Moose.pm" rel="nofollow noreferrer">Moose</a> also using roles. What I am having trouble understanding is the exact differences in both usage and implementation of Moose traits vs. roles.</p> <p>The <a href="http://search.cpan.org/~drolsky/Moose-0.87/lib/Moose/Cookbook/Extending/Recipe1.pod#ROLES_VS_TRAITS_VS_SUBCLASSES" rel="nofollow noreferrer">Moose documentation</a> states:</p> <blockquote> <p>It is important to understand that roles and traits are the same thing. A role can be used as a trait, and a trait is a role. The only thing that distinguishes the two is that a trait is packaged in a way that lets Moose resolve a short name to a class name. In other words, with a trait, the caller can refer to it by a short name like "Big", and Moose will resolve it to a class like MooseX::Embiggen::Meta::Attribute::Role::Big.</p> </blockquote> <p>It is my understanding that traits and roles are "the same". However, when implementing a basic test of the idea using the <code>use Moose -traits 'Foo'</code> syntax does not seem to do what I would expect. Surely I must be missing something here. </p> <p>This first example fails with "Can't locate object method 'foo'"</p> <pre><code>package MyApp::Meta::Class::Trait::HasTable; use Moose::Role; sub foo { warn 'foo' } package Moose::Meta::Class::Custom::Trait::HasTable; sub register_implementation { 'MyApp::Meta::Class::Trait::HasTable' } package MyApp::User; use Moose -traits =&gt; 'HasTable'; __PACKAGE__-&gt;foo(); #Can't locate object method 'foo' </code></pre> <p>Compared to this one (which does work):</p> <pre><code>package MyApp::Meta::Class::Trait::HasTable; use Moose::Role; sub foo { warn 'foo' } package Moose::Meta::Class::Custom::Trait::HasTable; sub register_implementation { 'MyApp::Meta::Class::Trait::HasTable' } package MyApp::User; use Moose; with 'MyApp::Meta::Class::Trait::HasTable'; __PACKAGE__-&gt;foo(); #foo </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload