6 Moose::Cookbook::Extending::Recipe2 - Providing a role for the base object class
10 package MooseX::Debugging;
17 use Moose::Util::MetaRole;
19 Moose::Exporter->setup_import_methods;
25 my $meta = Moose->init_meta(%options);
27 Moose::Util::MetaRole::apply_base_class_roles(
28 for_class => $options{for_class},
29 roles => ['MooseX::Debugging::Role::Object'],
35 package MooseX::Debugging::Role::Object;
39 after 'BUILD' => sub {
42 warn "Made a new " . ref $self . " object\n";
47 In this example, we provide a role for the base object class that adds
48 some simple debugging output. Every time an object is created, it
49 spits out a warning saying what type of object it was.
51 Obviously, a real debugging role would do something more interesting,
52 but this recipe is all about how we apply that role.
54 In this case, with the combination of L<Moose::Exporter> and
55 L<Moose::Util::MetaRole>, we ensure that when a module does C<S<use
56 MooseX::Debugging>>, it automatically gets the debugging role applied
57 to its base object class.
59 There are a few pieces of code worth looking at more closely.
61 Moose::Exporter->setup_import_methods;
63 This creates an C<import> method in the C<MooseX::Debugging>
64 package. Since we are not actually exporting anything, we do not pass
65 C<setup_import_methods> any parameters. However, we need to have an
66 C<import> method to ensure that our C<init_meta> method is called.
68 Then in our C<init_meta> method we have this line:
70 Moose->init_meta(%options);
72 This is a bit of boilerplate that almost every extension will
73 use. This ensures that the caller has a normal Moose metaclass
74 I<before> we go and add traits to it.
76 The C<< Moose->init_meta >> method does ensures that the caller has a
77 sane metaclass, and we don't want to replicate that logic in our
78 extension. If the C<< Moose->init_meta >> was already called (because
79 the caller did C<S<use Moose>> before using our extension), then
80 calling C<< Moose->init_meta >> again is effectively a no-op.
84 Dave Rolsky E<lt>autarch@urth.orgE<gt>
86 =head1 COPYRIGHT AND LICENSE
88 Copyright 2009 by Infinity Interactive, Inc.
90 L<http://www.iinteractive.com>
92 This library is free software; you can redistribute it and/or modify
93 it under the same terms as Perl itself.