Moose::Cookbook::Extending::Debugging\_BaseClassRole(3) User Contributed Perl Documentation Moose::Cookbook::Extending::Debugging\_BaseClassRole(3)

# [SYNOPSIS](#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";
  };
```

# [DESCRIPTION](#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 Moose::Exporter and Moose::Util::MetaRole, we ensure that when a module does "use MooseX::Debugging", 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 "import" method in the "MooseX::Debugging" package. Since we are not actually exporting anything, we do not pass "setup\_import\_methods" any parameters related to exports, but we need to have an "import" method to ensure that our "init\_meta" method is called. The "init\_meta" is created by "setup\_import\_methods" for us, since we passed the "base\_class\_roles" parameter. The generated "init\_meta" will in turn call Moose::Util::MetaRole::apply\_base\_class\_roles.

```
  sub BUILD {}
  after BUILD => sub {
      ...
  };
```

Due to the way role composition currently works, if the class that a role is composed into contains a "BUILD" method, then that will override the "BUILD" method in any roles it composes, which is typically not what you want. Using a method modifier on "BUILD" 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 "BUILD" method exists in the class.

2026-08-29 perl v5.44.0

---

Document: Moose::Cookbook::Extending::Debugging_BaseClassRole(3pm) from perl-moose 2.4000-r4 (Chainguard OS)
Source: https://github.com/moose/Moose
