Moose::Cookbook::Snack::BUILD - Custom initialization methods for Moose objects
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'); } } 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');
The BUILD() method allows you to write your own initialization methods for your Moose objects.
BUILD()
By convention, most objects in Perl are created by calling a new() method inside that object:
new()
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 new() method for you, how do you change the default behaivor of the new() method in Moose? This is what the BUILD() method was designed for.
package My::Moose::Class; sub BUILD { # object initialization code goes here... } package main; my $object = My::Moose::Class->new();
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?
Using type constraints via Moose::Util::TypeConstraints, you can verify simple relationships when an object is created:
package Triangle; use Moose; has
You would want to use the BUILD() method in order to verify more complex relationships:
package IsoscelesTriangle; use Moose;
If your object does not have a BUILD method, then Moose will skip trying to run it.
BUILD
(Taken from Moose::Object) The BUILDALL method will call every BUILD method in the inheritance hierarchy, and pass it a hash-ref of the the %params passed to the new() method.
BUILDALL
%params
Brian Manning <elspicyjack at gmail dot com>
Copyright 2006-2008 by Infinity Interactive, Inc.
http://www.iinteractive.com
This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself.
To install Moose, copy and paste the appropriate command in to your terminal.
cpanm
cpanm Moose
CPAN shell
perl -MCPAN -e shell install Moose
For more information on module installation, please visit the detailed CPAN module installation guide.