Slide 11
Slide 11 text
package Worker::Logging;
use Moose::Role;
has logger => (
is => ‘ro’,
isa => ‘Logger’,
builder => ‘_build_logger’,
handles => [‘log’],
);
sub _build_logger {
my $self = shift;
return Logger->new($self->_log_level);
}
requires ‘_log_level’;
before do_work => sub {
my ($self, $name) = @_;
$self->log(“About to do $name”);
};
11
11
128݄22ਫ༵
So to quickly cover what a role is, a role is a special kind of package. A role is not a class, because you can’t instantiate a role and roles do not participate in inheritance.
Instead, the way you interact with roles is fundamentally different.
A role has a set of methods, method modifiers (like before, after, and around, which you’ve probably used in Moose). Roles can also have attributes and all that attributes
support like a type constraint, a default value, laziness, etc.
Finally roles also support method requirements which is a way for the role to declare that anything that uses the role must fulfill some requirements.