NAME

Moose::Manual::Construction - Object construction (and destruction) with Moose

VERSION

version 2.2207

WHERE'S THE CONSTRUCTOR?

Do not define a new() method for your classes!

When you use Moose in your class, your class becomes a subclass of Moose::Object. The Moose::Object provides a new() method for your class. If you follow our recommendations in Moose::Manual::BestPractices and make your class immutable, then you actually get a class-specific new() method "inlined" in your class.

OBJECT CONSTRUCTION AND ATTRIBUTES

The Moose-provided constructor accepts a hash or hash reference of named parameters matching your attributes (actually, matching their init_args). This is just another way in which Moose keeps you from worrying how classes are implemented. Simply define a class and you're ready to start creating objects!

OBJECT CONSTRUCTION HOOKS

Moose lets you hook into object construction. You can validate an object's state, do logging, customize construction from parameters which do not match your attributes, or maybe allow non-hash(ref) constructor arguments. You can do this by creating BUILD and/or BUILDARGS methods.

If these methods exist in your class, Moose will arrange for them to be called as part of the object construction process.

BUILDARGS

The BUILDARGS method is called as a class method before an object is created. It will receive all of the arguments that were passed to new() as-is, and is expected to return a hash reference. This hash reference will be used to construct the object, so it should contain keys matching your attributes' names (well, init_args).

One common use for BUILDARGS is to accommodate a non-hash(ref) calling style. For example, we might want to allow our Person class to be called with a single argument of a social security number, Person->new($ssn).

Without a BUILDARGS method, Moose will complain, because it expects a hash or hash reference. We can use the BUILDARGS method to accommodate this calling style:

  around BUILDARGS => sub {
      my $orig  = shift;
      my $class = shift;

      if ( @_ == 1 && !ref $_[0] ) {
          return $class->$orig( ssn => $_[0] );
      }
      else {
          return $class->$orig(@_);
      }
  };

Note the call to $class->$orig. This will call the default BUILDARGS in Moose::Object. This method takes care of distinguishing between a hash reference and a plain hash for you.

BUILD

The BUILD method is called after an object is created. There are several reasons to use a BUILD method. One of the most common is to check that the object state is valid. While we can validate individual attributes through the use of types, we can't validate the state of a whole object that way.

  sub BUILD {
      my $self = shift;

      if ( $self->country_of_residence eq 'USA' ) {
          die 'All US residents must have an SSN'
              unless $self->has_ssn;
      }
  }

Another use of a BUILD method could be for logging or tracking object creation.

  sub BUILD {
      my $self = shift;

      debug( 'Made a new person - SSN = ', $self->ssn, );
  }

The BUILD method is called with the hash reference of the parameters passed to the constructor (after munging by BUILDARGS). This gives you a chance to do something with parameters that do not represent object attributes.

  sub BUILD {
      my $self = shift;
      my $args = shift;

      $self->add_friend(
          My::User->new(
              user_id => $args->{user_id},
          )
      );
  }

BUILD and parent classes

The interaction between multiple BUILD methods in an inheritance hierarchy is different from normal Perl methods. You should never call $self->SUPER::BUILD, nor should you ever apply a method modifier to BUILD. Roles are an exception to this rule, though: it's completely acceptable to apply a method modifier to BUILD in a role; you can even provide an empty BUILD subroutine in a role so the role is applicable even to classes without their own BUILD.

Moose arranges to have all of the BUILD methods in a hierarchy called when an object is constructed, from parents to children. This might be surprising at first, because it reverses the normal order of method inheritance.

The theory behind this is that BUILD methods can only be used for increasing specialization of a class's constraints, so it makes sense to call the least specific BUILD method first. Also, this is how Perl 6 does it.

OBJECT DESTRUCTION

Moose provides a hook for object destruction with the DEMOLISH method. As with BUILD, you should never explicitly call $self->SUPER::DEMOLISH. Moose will arrange for all of the DEMOLISH methods in your hierarchy to be called, from most to least specific.

Each DEMOLISH method is called with a single argument. This is a boolean value indicating whether or not this method was called as part of the global destruction process (when the Perl interpreter exits).

In most cases, Perl's built-in garbage collection is sufficient, and you won't need to provide a DEMOLISH method.

Error Handling During Destruction

The interaction of object destruction and Perl's global $@ and $? variables can be very confusing.

Moose always localizes $? when an object is being destroyed. This means that if you explicitly call exit, that exit code will be preserved even if an object's destructor makes a system call.

Moose also preserves $@ against any eval calls that may happen during object destruction. However, if an object's DEMOLISH method actually dies, Moose explicitly rethrows that error.

If you do not like this behavior, you will have to provide your own DESTROY method and use that instead of the one provided by Moose::Object. You can do this to preserve $@ and capture any errors from object destruction by creating an error stack.

AUTHORS

  • Stevan Little <stevan@cpan.org>

  • Dave Rolsky <autarch@urth.org>

  • Jesse Luehrs <doy@cpan.org>

  • Shawn M Moore <sartak@cpan.org>

  • יובל קוג'מן (Yuval Kogman) <nothingmuch@woobling.org>

  • Karen Etheridge <ether@cpan.org>

  • Florian Ragwitz <rafl@debian.org>

  • Hans Dieter Pearcey <hdp@cpan.org>

  • Chris Prather <chris@prather.org>

  • Matt S Trout <mstrout@cpan.org>

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.