3 sub _getglob { \*{$_[0]} }
4 sub _getstash { \%{"$_[0]::"} }
7 use warnings FATAL => 'all';
9 our $VERSION = '1.000001'; # 1.0.1
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_union_of_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
66 @{$INFO{$target}{not_methods}={}}{
67 '', map { *$_{CODE}||() } grep !ref($_), values %$stash
70 $APPLIED_TO{$target} = { $target => undef };
73 sub apply_role_to_package {
74 my ($me, $to, $role) = @_;
78 die "This is apply_role_to_package" if ref($to);
79 die "${role} is not a Role::Tiny" unless my $info = $INFO{$role};
81 $me->_check_requires($to, $role, @{$info->{requires}||[]});
83 $me->_install_methods($to, $role);
85 $me->_install_modifiers($to, $info->{modifiers});
87 # only add does() method to classes and only if they don't have one
88 if (not $INFO{$to} and not $to->can('does')) {
89 *{_getglob "${to}::does"} = \&does_role;
92 # copy our role list into the target's
93 @{$APPLIED_TO{$to}||={}}{keys %{$APPLIED_TO{$role}}} = ();
96 sub apply_roles_to_object {
97 my ($me, $object, @roles) = @_;
98 die "No roles supplied!" unless @roles;
99 my $class = ref($object);
100 bless($object, $me->create_class_with_roles($class, @roles));
104 sub create_class_with_roles {
105 my ($me, $superclass, @roles) = @_;
107 die "No roles supplied!" unless @roles;
110 '__WITH__', $superclass, my $compose_name = join '__AND__', @roles
113 return $new_name if $COMPOSED{class}{$new_name};
115 foreach my $role (@roles) {
117 die "${role} is not a Role::Tiny" unless $INFO{$role};
126 my @composable = map $me->_composable_package_for($_), reverse @roles;
128 *{_getglob("${new_name}::ISA")} = [ @composable, $superclass ];
130 my @info = map $INFO{$_}, @roles;
132 $me->_check_requires(
133 $new_name, $compose_name,
134 do { my %h; @h{map @{$_->{requires}||[]}, @info} = (); keys %h }
137 *{_getglob "${new_name}::does"} = \&does_role unless $new_name->can('does');
139 @{$APPLIED_TO{$new_name}||={}}{
140 map keys %{$APPLIED_TO{$_}}, @roles
143 $COMPOSED{class}{$new_name} = 1;
147 sub apply_union_of_roles_to_package {
148 my ($me, $to, @roles) = @_;
150 return $me->apply_role_to_package($to, $roles[0]) if @roles == 1;
152 my %conflicts = %{$me->_union_info_for(@roles)->{conflicts}};
153 delete $conflicts{$_} for $me->_concrete_methods_of($to);
154 if (keys %conflicts) {
158 "Due to a method name conflict between roles "
159 ."'".join(' and ', sort values %{$conflicts{$_}})."'"
160 .", the method '$_' must be implemented by '${to}'"
164 $me->apply_role_to_package($to, $_) for @roles;
165 $APPLIED_TO{$to}{join('|',@roles)} = 1;
168 sub _union_info_for {
169 my ($me, @roles) = @_;
170 $UNION_INFO{join('|',@roles)} ||= do {
171 _load_module($_) for @roles;
173 foreach my $role (@roles) {
174 my $this_methods = $me->_concrete_methods_of($role);
175 $methods{$_}{$this_methods->{$_}} = $role for keys %$this_methods;
177 delete $methods{$_} for grep keys(%{$methods{$_}}) == 1, keys %methods;
178 +{ conflicts => \%methods }
182 sub _composable_package_for {
183 my ($me, $role) = @_;
184 my $composed_name = 'Role::Tiny::_COMPOSABLE::'.$role;
185 return $composed_name if $COMPOSED{role}{$composed_name};
186 $me->_install_methods($composed_name, $role);
187 my $base_name = $composed_name.'::_BASE';
188 *{_getglob("${composed_name}::ISA")} = [ $base_name ];
189 my $modifiers = $INFO{$role}{modifiers}||[];
191 foreach my $modified (
192 do { my %h; @h{map $_->[1], @$modifiers} = (); keys %h }
194 push @mod_base, "sub ${modified} { shift->next::method(\@_) }";
199 eval(my $code = join "\n", "package ${base_name};", @mod_base);
200 $e = "Evaling failed: $@\nTrying to eval:\n${code}" if $@;
203 $me->_install_modifiers($composed_name, $modifiers);
204 $COMPOSED{role}{$composed_name} = 1;
205 return $composed_name;
208 sub _check_requires {
209 my ($me, $to, $name, @requires) = @_;
210 if (my @requires_fail = grep !$to->can($_), @requires) {
211 # role -> role, add to requires, role -> class, error out
212 if (my $to_info = $INFO{$to}) {
213 push @{$to_info->{requires}||=[]}, @requires_fail;
215 die "Can't apply ${name} to ${to} - missing ".join(', ', @requires_fail);
220 sub _concrete_methods_of {
221 my ($me, $role) = @_;
222 my $info = $INFO{$role};
223 # grab role symbol table
224 my $stash = do { no strict 'refs'; \%{"${role}::"}};
225 my $not_methods = $info->{not_methods};
227 # grab all code entries that aren't in the not_methods list
229 my $code = *{$stash->{$_}}{CODE};
230 # rely on the '' key we added in import for "no code here"
231 exists $not_methods->{$code||''} ? () : ($_ => $code)
232 } grep !ref($stash->{$_}), keys %$stash
236 sub methods_provided_by {
237 my ($me, $role) = @_;
238 die "${role} is not a Role::Tiny" unless my $info = $INFO{$role};
239 (keys %{$me->_concrete_methods_of($role)}, @{$info->{requires}||[]});
242 sub _install_methods {
243 my ($me, $to, $role) = @_;
245 my $info = $INFO{$role};
247 my $methods = $me->_concrete_methods_of($role);
249 # grab target symbol table
250 my $stash = do { no strict 'refs'; \%{"${to}::"}};
252 # determine already extant methods of target
255 +(ref($stash->{$_}) || *{$stash->{$_}}{CODE}),
259 foreach my $i (grep !exists $has_methods{$_}, keys %$methods) {
261 *{_getglob "${to}::${i}"} = $methods->{$i};
265 sub _install_modifiers {
266 my ($me, $to, $modifiers) = @_;
267 if (my $info = $INFO{$to}) {
268 push @{$info->{modifiers}}, @{$modifiers||[]};
270 foreach my $modifier (@{$modifiers||[]}) {
271 $me->_install_single_modifier($to, @$modifier);
276 sub _install_single_modifier {
277 my ($me, @args) = @_;
278 Class::Method::Modifiers::install_modifier(@args);
282 my ($proto, $role) = @_;
283 return exists $APPLIED_TO{ref($proto)||$proto}{$role};
290 Role::Tiny - Roles. Like a nouvelle cuisine portion size slice of Moose.
302 around baz => sub { ... }
310 use Role::Tiny::With;
312 # bar gets imported, but not foo
317 # baz is wrapped in the around modifier by Class::Method::Modifiers
322 If you wanted attributes as well, look at L<Moo::Role>.
326 C<Role::Tiny> is a minimalist role composition tool.
328 =head1 ROLE COMPOSITION
330 Role composition can be thought of as much more clever and meaningful multiple
331 inheritance. The basics of this implementation of roles is:
337 If a method is already defined on a class, that method will not be composed in
342 If a method that the role L</requires> to be implemented is not implemented,
343 role application will fail loudly.
347 Unlike L<Class::C3>, where the B<last> class inherited from "wins," role
348 composition is the other way around, where first wins. In a more complete
349 system (see L<Moose>) roles are checked to see if they clash. The goal of this
350 is to be much simpler, hence disallowing composition of multiple roles at once.
354 =head2 apply_role_to_package
356 Role::Tiny->apply_role_to_package('Some::Package', 'Some::Role');
358 Composes role with package. See also L<Role::Tiny::With>.
360 =head2 apply_roles_to_object
362 Role::Tiny->apply_roles_to_object($foo, qw(Some::Role1 Some::Role2));
364 Composes roles in order into object directly. Object is reblessed into the
367 =head2 create_class_with_roles
369 Role::Tiny->create_class_with_roles('Some::Base', qw(Some::Role1 Some::Role2));
371 Creates a new class based on base, with the roles composed into it in order.
372 New class is returned.
378 if (Role::Tiny::does_role($foo, 'Some::Role')) {
382 Returns true if class has been composed with role.
384 This subroutine is also installed as ->does on any class a Role::Tiny is
385 composed into unless that class already has an ->does method, so
387 if ($foo->does('Some::Role')) {
391 will work for classes but to test a role, one must use ::does_role directly
393 =head1 IMPORTED SUBROUTINES
397 requires qw(foo bar);
399 Declares a list of methods that must be defined to compose role.
406 Composes another role into the current role. Only one role may be composed in
407 at a time to allow the code to remain as simple as possible.
411 before foo => sub { ... };
413 See L<< Class::Method::Modifiers/before method(s) => sub { ... } >> for full
416 Note that since you are not required to use method modifiers,
417 L<Class::Method::Modifiers> is lazily loaded and we do not declare it as
418 a dependency. If your L<Role::Tiny> role uses modifiers you must depend on
419 both L<Class::Method::Modifiers> and L<Role::Tiny>.
423 around foo => sub { ... };
425 See L<< Class::Method::Modifiers/around method(s) => sub { ... } >> for full
428 Note that since you are not required to use method modifiers,
429 L<Class::Method::Modifiers> is lazily loaded and we do not declare it as
430 a dependency. If your L<Role::Tiny> role uses modifiers you must depend on
431 both L<Class::Method::Modifiers> and L<Role::Tiny>.
435 after foo => sub { ... };
437 See L<< Class::Method::Modifiers/after method(s) => sub { ... } >> for full
440 Note that since you are not required to use method modifiers,
441 L<Class::Method::Modifiers> is lazily loaded and we do not declare it as
442 a dependency. If your L<Role::Tiny> role uses modifiers you must depend on
443 both L<Class::Method::Modifiers> and L<Role::Tiny>.
447 L<Role::Tiny> is the attribute-less subset of L<Moo::Role>; L<Moo::Role> is
448 a meta-protocol-less subset of the king of role systems, L<Moose::Role>.
450 If you don't want method modifiers and do want to be forcibly restricted
451 to a single role application per class, Ovid's L<Role::Basic> exists. But
452 Stevan Little (the L<Moose> author) and I are both still convinced that
457 mst - Matt S. Trout (cpan:MSTROUT) <mst@shadowcat.co.uk>
461 dg - David Leadbeater (cpan:DGL) <dgl@dgl.cx>
463 frew - Arthur Axel "fREW" Schmidt (cpan:FREW) <frioux@gmail.com>
465 hobbs - Andrew Rodland (cpan:ARODLAND) <arodland@cpan.org>
467 jnap - John Napiorkowski (cpan:JJNAPIORK) <jjn1056@yahoo.com>
469 ribasushi - Peter Rabbitson (cpan:RIBASUSHI) <ribasushi@cpan.org>
471 chip - Chip Salzenberg (cpan:CHIPS) <chip@pobox.com>
473 ajgb - Alex J. G. BurzyĆski (cpan:AJGB) <ajgb@cpan.org>
475 doy - Jesse Luehrs (cpan:DOY) <doy at tozt dot net>
477 perigrin - Chris Prather (cpan:PERIGRIN) <chris@prather.org>
481 Copyright (c) 2010-2012 the Role::Tiny L</AUTHOR> and L</CONTRIBUTORS>
486 This library is free software and may be distributed under the same terms