=pod =head1 NAME Moose::Cookbook::Snack::BUILD - Custom initialization methods for Moose objects =head1 SYNOPSIS package Build::Demo; use Moose; # once the object has been created, don't allow # changes to 'example_file' has 'example_file' => (is => 'ro', required => 1); sub BUILD { my $self = shift; # create the object only if the 'example_file' exists if (-e $self->example_file) { return $self; } else { die('ERROR: file _' . $self->example_file . '_ does not exist'); } } # sub BUILD package main; use Moose; # the name of this script, which works my $first_test = Build::Demo->new(example_file => $0); # this should fail (unless there's a file named 'foo' # in the current directory) my $second_test = Build::Demo->new(example_file => 'foo'); =head1 DESCRIPTION The C method allows you to write your own initialization methods for your Moose objects. =head2 Creating new objects in Perl and Moose By convention, most objects in Perl are created by calling a C method inside that object: package My::Perl::Class; sub new { # object blessing and initialization code goes here... } package main; my $object = My::Perl::Class->new(); Moose is no different in this respect. However, since Moose handles the C method for you, how do you change the default behaivor of the C method in Moose? This is what the C method was designed for. package My::Moose::Class; sub BUILD { # object initialization code goes here... } package main; my $object = My::Moose::Class->new(); =head2 Why would you want a custom constructor? If your object needs to verify some behaivor or internal state before it is created, a good time to do that is when the object is being created. Why waste resources (CPU, memory) on objects that won't work because of missing resources? =head2 BUILD method is run only if it is defined in the object If your object does not have a C method, then Moose will skip trying to run it. =head2 What is 'BUILDALL'? (Taken from L) The C method will call every BUILD method in the inheritance hierarchy, and pass it a hash-ref of the the %params passed to the C method. =head1 SEE ALSO =over 4 =item L - The base object for Moose (BUILDALL) =item L - Frequently asked questions about Moose (How do I write custom constructors with Moose?) =item L - Subtypes, and modeling a simple Company class heirarchy (Example usage of BUILD in action) =item L - For when things go wrong with Moose ('Roles' section describes BUILD/BUILDALL) =back =head1 AUTHOR Brian Manning =head1 COPYRIGHT AND LICENSE Copyright (c)2008 by Infinity Interactive, Inc. This documentation is free software; you can redistribute it and/or modify it under the same terms as Perl itself. =cut