3 sub _getglob { \*{$_[0]} }
4 sub _getstash { \%{"$_[0]::"} }
7 use warnings FATAL => 'all';
9 our $VERSION = '1.001002'; # 1.1.2
10 $VERSION = eval $VERSION;
17 # Module state workaround totally stolen from Zefram's Module::Runtime.
20 *_WORK_AROUND_BROKEN_MODULE_STATE = "$]" < 5.009 ? sub(){1} : sub(){0};
23 sub Role::Tiny::__GUARD__::DESTROY {
24 delete $INC{$_[0]->[0]} if @{$_[0]};
28 (my $proto = $_[0]) =~ s/::/\//g;
30 return 1 if $INC{$proto};
31 # can't just ->can('can') because a sub-package Foo::Bar::Baz
32 # creates a 'Baz::' key in Foo::Bar's symbol table
33 return 1 if grep !/::$/, keys %{_getstash($_[0])||{}};
34 my $guard = _WORK_AROUND_BROKEN_MODULE_STATE
35 && bless([ $proto ], 'Role::Tiny::__GUARD__');
37 pop @$guard if _WORK_AROUND_BROKEN_MODULE_STATE;
45 warnings->import(FATAL => 'all');
46 return if $INFO{$target}; # already exported into this package
47 # get symbol table reference
48 my $stash = do { no strict 'refs'; \%{"${target}::"} };
49 # install before/after/around subs
50 foreach my $type (qw(before after around)) {
51 *{_getglob "${target}::${type}"} = sub {
52 require Class::Method::Modifiers;
53 push @{$INFO{$target}{modifiers}||=[]}, [ $type => @_ ];
56 *{_getglob "${target}::requires"} = sub {
57 push @{$INFO{$target}{requires}||=[]}, @_;
59 *{_getglob "${target}::with"} = sub {
60 $me->apply_roles_to_package($target, @_);
62 # grab all *non-constant* (stash slot is not a scalarref) subs present
63 # in the symbol table and store their refaddrs (no need to forcibly
64 # inflate constant subs into real subs) - also add '' to here (this
65 # is used later) with a map to the coderefs in case of copying or re-use
66 my @not_methods = ('', map { *$_{CODE}||() } grep !ref($_), values %$stash);
67 @{$INFO{$target}{not_methods}={}}{@not_methods} = @not_methods;
69 $APPLIED_TO{$target} = { $target => undef };
72 sub apply_single_role_to_package {
73 my ($me, $to, $role) = @_;
77 die "This is apply_role_to_package" if ref($to);
78 die "${role} is not a Role::Tiny" unless my $info = $INFO{$role};
80 $me->_check_requires($to, $role, @{$info->{requires}||[]});
82 $me->_install_methods($to, $role);
84 $me->_install_modifiers($to, $info->{modifiers});
86 # only add does() method to classes and only if they don't have one
87 if (not $INFO{$to} and not $to->can('does')) {
88 *{_getglob "${to}::does"} = \&does_role;
91 # copy our role list into the target's
92 @{$APPLIED_TO{$to}||={}}{keys %{$APPLIED_TO{$role}}} = ();
95 sub apply_roles_to_object {
96 my ($me, $object, @roles) = @_;
97 die "No roles supplied!" unless @roles;
98 my $class = ref($object);
99 bless($object, $me->create_class_with_roles($class, @roles));
103 sub create_class_with_roles {
104 my ($me, $superclass, @roles) = @_;
106 die "No roles supplied!" unless @roles;
110 $seen{$_}++ for @roles;
111 if (my @dupes = grep $seen{$_} > 1, @roles) {
112 die "Duplicated roles: ".join(', ', @dupes);
117 '__WITH__', $superclass, my $compose_name = join '__AND__', @roles
120 return $new_name if $COMPOSED{class}{$new_name};
122 foreach my $role (@roles) {
124 die "${role} is not a Role::Tiny" unless $INFO{$role};
133 my @composable = map $me->_composable_package_for($_), reverse @roles;
135 *{_getglob("${new_name}::ISA")} = [ @composable, $superclass ];
137 my @info = map $INFO{$_}, @roles;
139 $me->_check_requires(
140 $new_name, $compose_name,
141 do { my %h; @h{map @{$_->{requires}||[]}, @info} = (); keys %h }
144 *{_getglob "${new_name}::does"} = \&does_role unless $new_name->can('does');
146 @{$APPLIED_TO{$new_name}||={}}{
147 map keys %{$APPLIED_TO{$_}}, @roles
150 $COMPOSED{class}{$new_name} = 1;
154 # preserved for compat, and apply_roles_to_package calls it to allow an
155 # updated Role::Tiny to use a non-updated Moo::Role
157 sub apply_role_to_package { shift->apply_single_role_to_package(@_) }
159 sub apply_roles_to_package {
160 my ($me, $to, @roles) = @_;
162 return $me->apply_role_to_package($to, $roles[0]) if @roles == 1;
164 my %conflicts = %{$me->_composite_info_for(@roles)->{conflicts}};
165 delete $conflicts{$_} for $me->_concrete_methods_of($to);
166 if (keys %conflicts) {
170 "Due to a method name conflict between roles "
171 ."'".join(' and ', sort values %{$conflicts{$_}})."'"
172 .", the method '$_' must be implemented by '${to}'"
176 delete $INFO{$to}{methods}; # reset since we're about to add methods
177 $me->apply_role_to_package($to, $_) for @roles;
178 $APPLIED_TO{$to}{join('|',@roles)} = 1;
181 sub _composite_info_for {
182 my ($me, @roles) = @_;
183 $COMPOSITE_INFO{join('|', sort @roles)} ||= do {
184 _load_module($_) for @roles;
186 foreach my $role (@roles) {
187 my $this_methods = $me->_concrete_methods_of($role);
188 $methods{$_}{$this_methods->{$_}} = $role for keys %$this_methods;
190 delete $methods{$_} for grep keys(%{$methods{$_}}) == 1, keys %methods;
191 +{ conflicts => \%methods }
195 sub _composable_package_for {
196 my ($me, $role) = @_;
197 my $composed_name = 'Role::Tiny::_COMPOSABLE::'.$role;
198 return $composed_name if $COMPOSED{role}{$composed_name};
199 $me->_install_methods($composed_name, $role);
200 my $base_name = $composed_name.'::_BASE';
201 *{_getglob("${composed_name}::ISA")} = [ $base_name ];
202 my $modifiers = $INFO{$role}{modifiers}||[];
204 foreach my $modified (
205 do { my %h; @h{map $_->[1], @$modifiers} = (); keys %h }
207 push @mod_base, "sub ${modified} { shift->next::method(\@_) }";
212 eval(my $code = join "\n", "package ${base_name};", @mod_base);
213 $e = "Evaling failed: $@\nTrying to eval:\n${code}" if $@;
216 $me->_install_modifiers($composed_name, $modifiers);
217 $COMPOSED{role}{$composed_name} = 1;
218 return $composed_name;
221 sub _check_requires {
222 my ($me, $to, $name, @requires) = @_;
223 if (my @requires_fail = grep !$to->can($_), @requires) {
224 # role -> role, add to requires, role -> class, error out
225 if (my $to_info = $INFO{$to}) {
226 push @{$to_info->{requires}||=[]}, @requires_fail;
228 die "Can't apply ${name} to ${to} - missing ".join(', ', @requires_fail);
233 sub _concrete_methods_of {
234 my ($me, $role) = @_;
235 my $info = $INFO{$role};
236 # grab role symbol table
237 my $stash = do { no strict 'refs'; \%{"${role}::"}};
238 # reverse so our keys become the values (captured coderefs) in case
239 # they got copied or re-used since
240 my $not_methods = { reverse %{$info->{not_methods}} };
241 $info->{methods} ||= +{
242 # grab all code entries that aren't in the not_methods list
244 my $code = *{$stash->{$_}}{CODE};
245 # rely on the '' key we added in import for "no code here"
246 exists $not_methods->{$code||''} ? () : ($_ => $code)
247 } grep !ref($stash->{$_}), keys %$stash
251 sub methods_provided_by {
252 my ($me, $role) = @_;
253 die "${role} is not a Role::Tiny" unless my $info = $INFO{$role};
254 (keys %{$me->_concrete_methods_of($role)}, @{$info->{requires}||[]});
257 sub _install_methods {
258 my ($me, $to, $role) = @_;
260 my $info = $INFO{$role};
262 my $methods = $me->_concrete_methods_of($role);
264 # grab target symbol table
265 my $stash = do { no strict 'refs'; \%{"${to}::"}};
267 # determine already extant methods of target
270 +(ref($stash->{$_}) || *{$stash->{$_}}{CODE}),
274 foreach my $i (grep !exists $has_methods{$_}, keys %$methods) {
276 *{_getglob "${to}::${i}"} = $methods->{$i};
280 sub _install_modifiers {
281 my ($me, $to, $modifiers) = @_;
282 if (my $info = $INFO{$to}) {
283 push @{$info->{modifiers}}, @{$modifiers||[]};
285 foreach my $modifier (@{$modifiers||[]}) {
286 $me->_install_single_modifier($to, @$modifier);
291 sub _install_single_modifier {
292 my ($me, @args) = @_;
293 Class::Method::Modifiers::install_modifier(@args);
297 my ($proto, $role) = @_;
298 return exists $APPLIED_TO{ref($proto)||$proto}{$role};
305 Role::Tiny - Roles. Like a nouvelle cuisine portion size slice of Moose.
317 around baz => sub { ... }
325 use Role::Tiny::With;
327 # bar gets imported, but not foo
332 # baz is wrapped in the around modifier by Class::Method::Modifiers
337 If you wanted attributes as well, look at L<Moo::Role>.
341 C<Role::Tiny> is a minimalist role composition tool.
343 =head1 ROLE COMPOSITION
345 Role composition can be thought of as much more clever and meaningful multiple
346 inheritance. The basics of this implementation of roles is:
352 If a method is already defined on a class, that method will not be composed in
357 If a method that the role L</requires> to be implemented is not implemented,
358 role application will fail loudly.
362 Unlike L<Class::C3>, where the B<last> class inherited from "wins," role
363 composition is the other way around, where the class wins. If multiple roles
364 are applied in a single call (single with statement), then if any of their
365 provided methods clash, an exception is raised unless the class provides
366 a method since this conflict indicates a potential problem.
368 =head1 IMPORTED SUBROUTINES
372 requires qw(foo bar);
374 Declares a list of methods that must be defined to compose role.
380 with 'Some::Role1', 'Some::Role2';
382 Composes another role into the current role (or class via L<Role::Tiny::With>).
384 If you have conflicts and want to resolve them in favour of Some::Role1 you
390 If you have conflicts and want to resolve different conflicts in favour of
391 different roles, please refactor your codebase.
395 before foo => sub { ... };
397 See L<< Class::Method::Modifiers/before method(s) => sub { ... } >> for full
400 Note that since you are not required to use method modifiers,
401 L<Class::Method::Modifiers> is lazily loaded and we do not declare it as
402 a dependency. If your L<Role::Tiny> role uses modifiers you must depend on
403 both L<Class::Method::Modifiers> and L<Role::Tiny>.
407 around foo => sub { ... };
409 See L<< Class::Method::Modifiers/around method(s) => sub { ... } >> for full
412 Note that since you are not required to use method modifiers,
413 L<Class::Method::Modifiers> is lazily loaded and we do not declare it as
414 a dependency. If your L<Role::Tiny> role uses modifiers you must depend on
415 both L<Class::Method::Modifiers> and L<Role::Tiny>.
419 after foo => sub { ... };
421 See L<< Class::Method::Modifiers/after method(s) => sub { ... } >> for full
424 Note that since you are not required to use method modifiers,
425 L<Class::Method::Modifiers> is lazily loaded and we do not declare it as
426 a dependency. If your L<Role::Tiny> role uses modifiers you must depend on
427 both L<Class::Method::Modifiers> and L<Role::Tiny>.
433 if (Role::Tiny::does_role($foo, 'Some::Role')) {
437 Returns true if class has been composed with role.
439 This subroutine is also installed as ->does on any class a Role::Tiny is
440 composed into unless that class already has an ->does method, so
442 if ($foo->does('Some::Role')) {
446 will work for classes but to test a role, one must use ::does_role directly
450 =head2 apply_roles_to_package
452 Role::Tiny->apply_roles_to_package(
453 'Some::Package', 'Some::Role', 'Some::Other::Role'
456 Composes role with package. See also L<Role::Tiny::With>.
458 =head2 apply_roles_to_object
460 Role::Tiny->apply_roles_to_object($foo, qw(Some::Role1 Some::Role2));
462 Composes roles in order into object directly. Object is reblessed into the
465 =head2 create_class_with_roles
467 Role::Tiny->create_class_with_roles('Some::Base', qw(Some::Role1 Some::Role2));
469 Creates a new class based on base, with the roles composed into it in order.
470 New class is returned.
474 L<Role::Tiny> is the attribute-less subset of L<Moo::Role>; L<Moo::Role> is
475 a meta-protocol-less subset of the king of role systems, L<Moose::Role>.
477 If you don't want method modifiers and do want to be forcibly restricted
478 to a single role application per class, Ovid's L<Role::Basic> exists. But
479 Stevan Little (the L<Moose> author) and I don't find the additional
480 restrictions to be amazingly helpful in most cases; L<Role::Basic>'s choices
481 are more a guide to what you should prefer doing, to our mind, rather than
482 something that needs to be enforced.
486 mst - Matt S. Trout (cpan:MSTROUT) <mst@shadowcat.co.uk>
490 dg - David Leadbeater (cpan:DGL) <dgl@dgl.cx>
492 frew - Arthur Axel "fREW" Schmidt (cpan:FREW) <frioux@gmail.com>
494 hobbs - Andrew Rodland (cpan:ARODLAND) <arodland@cpan.org>
496 jnap - John Napiorkowski (cpan:JJNAPIORK) <jjn1056@yahoo.com>
498 ribasushi - Peter Rabbitson (cpan:RIBASUSHI) <ribasushi@cpan.org>
500 chip - Chip Salzenberg (cpan:CHIPS) <chip@pobox.com>
502 ajgb - Alex J. G. BurzyĆski (cpan:AJGB) <ajgb@cpan.org>
504 doy - Jesse Luehrs (cpan:DOY) <doy at tozt dot net>
506 perigrin - Chris Prather (cpan:PERIGRIN) <chris@prather.org>
508 Mithaldu - Christian Walde (cpan:MITHALDU) <walde.christian@googlemail.com>
512 Copyright (c) 2010-2012 the Role::Tiny L</AUTHOR> and L</CONTRIBUTORS>
517 This library is free software and may be distributed under the same terms