# PODNAME: Moose::Cookbook::Extending::Debugging_BaseClassRole # ABSTRACT: Providing a role for the base object class __END__ =pod =encoding UTF-8 =head1 NAME Moose::Cookbook::Extending::Debugging_BaseClassRole - Providing a role for the base object class =head1 VERSION version 2.1405 =head1 SYNOPSIS package MooseX::Debugging; use Moose::Exporter; Moose::Exporter->setup_import_methods( base_class_roles => ['MooseX::Debugging::Role::Object'], ); package MooseX::Debugging::Role::Object; use Moose::Role; sub BUILD {} after BUILD => sub { my $self = shift; warn "Made a new " . ( ref $self ) . " object\n"; }; =head1 DESCRIPTION In this example, we provide a role for the base object class that adds some simple debugging output. Every time an object is created, it spits out a warning saying what type of object it was. Obviously, a real debugging role would do something more interesting, but this recipe is all about how we apply that role. In this case, with the combination of L and L, we ensure that when a module does C>, it automatically gets the debugging role applied to its base object class. There are a few pieces of code worth looking at more closely. Moose::Exporter->setup_import_methods( base_class_roles => ['MooseX::Debugging::Role::Object'], ); This creates an C method in the C package. Since we are not actually exporting anything, we do not pass C any parameters related to exports, but we need to have an C method to ensure that our C method is called. The C is created by C for us, since we passed the C parameter. The generated C will in turn call L. sub BUILD {} after BUILD => sub { ... }; Due to the way role composition currently works, if the class that a role is composed into contains a C method, then that will override the C method in any roles it composes, which is typically not what you want. Using a method modifier on C avoids this issue, since method modifiers compose together rather than being overridden. Method modifiers require that a method exists in order to wrap, however, so we also provide a stub method to wrap if no C method exists in the class. =for testing-SETUP use Test::Requires 'Test::Output'; =begin testing { package Debugged; use Moose; MooseX::Debugging->import; } stderr_is( sub { Debugged->new }, "Made a new Debugged object\n", 'got expected output from debugging role' ); =end testing =head1 AUTHORS =over 4 =item * Stevan Little =item * Dave Rolsky =item * Jesse Luehrs =item * Shawn M Moore =item * יובל קוג'מן (Yuval Kogman) =item * Karen Etheridge =item * Florian Ragwitz =item * Hans Dieter Pearcey =item * Chris Prather =item * Matt S Trout =back =head1 COPYRIGHT AND LICENSE This software is copyright (c) 2006 by Infinity Interactive, Inc.. This is free software; you can redistribute it and/or modify it under the same terms as the Perl 5 programming language system itself. =cut