=pod =head1 NAME Moose::Cookbook::Extending::Recipe2 - Providing a role for the base object class =head1 SYNOPSIS package MooseX::Debugging; use strict; use warnings; use Moose (); use Moose::Exporter; use Moose::Util::MetaRole; use MooseX::Debugging::Role::Object; Moose::Exporter->setup_import_methods; sub init_meta { shift; my %options = @_; Moose->init_meta(%options); Moose::Util::MetaRole::apply_base_class_roles( for_class => $options{for_class}, roles => ['MooseX::Debugging::Role::Object'], ); } package MooseX::Debugging::Role::Object; 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; This creates an C method in the C package. Since we are not actually exporting anything, we do not pass C any parameters. However, we need to have an C method to ensure that our C method is called. Then in our C method we have this line: Moose->init_meta(%options); This is a bit of boilerplate that almost every extension will use. This ensures that the caller has a normal Moose metaclass I we go and add traits to it. The C<< Moose->init_meta >> method does ensures that the caller has a sane metaclass, and we don't want to replicate that logic in our extension. If the C<< Moose->init_meta >> was already called (because the caller did C> before using our extension), then calling C<< Moose->init_meta >> again is effectively a no-op. =head1 AUTHOR Dave Rolsky Eautarch@urth.orgE =head1 COPYRIGHT AND LICENSE Copyright 2009 by Infinity Interactive, Inc. L This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself. =cut