Tom,

The new_object method on the metaclass does not call BUILD, this is only called by Moose::Object::new, and more specifically Moose::Object::BUILDALL. The BUILD initialization feature is a part of Moose::Object and not the underlying MOP.

The thinking is that the division of responsibility should function like this:

- The class is responsible for the creation of object instances.
- The base object is responsible for the object initialization.

By doing this it makes it much easier for the end user to override (or just exert finer control over) object initialization features with simple subclassing, rather then requiring any MOP diving.

Basically, your suspicions about what purpose Moose::Meta::Class serves are correct though, it exists to build classes with and then to later alter those classes.

- Stevan


On Aug 27, 2008, at 9:11 PM, Bald Man Tom wrote:

Greetings. I was leafing through the Moose documentation the other day when I stumbled across Moose::Meta::Class. If I understand correctly, one of the things I can do with this module is create metaclasses, then use those to create new objects. However, when I do so, the BUILD subs don't seem to be called in the same way as when I create objects from "traditional" Moose classes:

Consider this bogus example:

---

#! perl

use strict;
use warnings;

package My::Class;
use Moose;

sub BUILD { print "BUILD for My::Class\n"; }

package My::SubClass;

use Moose;
extends 'My::Class';
sub BUILD { print "BUILD for My::SubClass\n"; }

package main;

use Moose::Meta::Class;

my $mc = Moose::Meta::Class->create( 'My::MetaSubClass',
   superclasses => [ 'My::Class' ],
   methods => {
       BUILD   => sub { print "BUILD for My::MetaSubClass\n"; },
   },
);

print "Creating a new object from the metaclass\n";
my $obj_from_metaclass = $mc->new_object();
print "Creation complete\n";

print "\nCreating a new object from the My::SubClass\n";
my $obj_from_subclass = My::SubClass->new();
print "Creation complete\n";

---

When I run this, I get the following output:

---

Creating a new object from the metaclass
Creation complete

Creating a new object from the My::SubClass
BUILD for My::Class
BUILD for My::SubClass
Creation complete


---

I would have expected the BUILD subs for My::Class and My::MetaSubClass to have been called when I called $mc->new_object (). Of course, I can do this manually by using $obj_from_metaclass- >BUILDALL().

Is my expectation of the BUILD subs being run unfounded? Or, more likely, am I completely misunderstanding the intent of Moose::Meta::Class in the first place?

Thanks!
Tom

Reply via email to