-
-
07 Nov 2021 03:41:58 UTC
- Distribution: Moose
- Source (raw)
- Browse (raw)
- Changes
- Homepage
- How to Contribute
- Repository
- Issues (71)
- Testers (2836 / 3 / 1)
- Kwalitee
Bus factor: 3- 92.11% Coverage
- License: perl_5
- Perl: v5.8.3
- Activity
24 month- Tools
- Download (881.54KB)
- MetaCPAN Explorer
- Permissions
- Subscribe to distribution
- Permalinks
- This version
- Latest version
and 142 contributors-
Stevan Little
-
Dave Rolsky
-
Jesse Luehrs
-
Shawn M Moore
-
יובל קוג'מן (Yuval Kogman)
-
Florian Ragwitz
-
Hans Dieter Pearcey
-
Chris Prather
-
Matt S Trout
-
Upasana Shukla
-
Graham Knop
-
Tomas Doran
-
Ricardo Signes
-
Guillermo Roditi
-
John Napiorkowski
-
Aankhen
-
Todd Hepler
-
Jonathan Rockway
-
Gerda Shank
-
Perlover
-
Shlomi Fish
-
Brad Bowman
-
Justin Hunter
-
Kent Fredric
-
Paul Driver
-
Anders Nor Berle
-
Brian Manning
-
gfx
-
Jay Hannah
-
Lars Dɪᴇᴄᴋᴏᴡ 迪拉斯
-
Leon Brocard
-
Olivier Mengué
-
Rafael Kitover
-
Christian Hansen
-
Cory Watson
-
Dagfinn Ilmari Mannsåker
-
Paul Jamieson Fenwick
-
Robert Buels
-
Dan Dascalescu
-
Marcel Grünauer
-
Scott McWhirter
-
Ævar Arnfjörð Bjarmason
-
Daisuke Maki (lestrrat)
-
Dylan William Hardison
-
Patrick Donelan
-
Stefan O'Rear
-
Tokuhiro Matsuno
-
Ash Berlin
-
Chris Weyl
-
Eric Wilhelm
-
Jess Robinson
-
Marc Mims
-
Marcus Ramberg
-
Mark Allen
-
Mateu X Hunter
-
matthof
-
Robert 'phaylon' Sedlacek
-
Zachary Lome
-
Aran Clary Deltac
-
Chip
-
Christopher J. Madsen
-
Curtis Jewell
-
Evan Carroll
-
Mark A. Stratman
-
Mark Fowler
-
Matthew Horsfall
-
mauke
-
Michael LaGrasta
-
Michael Rykov
-
Mike Whitaker
-
Moritz Onken
-
Nelo Onyiah
-
Nick Perez
-
Robert Boone
-
Robin V
-
rodrigolive
-
shelling
-
Thomas Sibley
-
Tom Hukins
-
Wallace Reis
-
Aaron Cohen
-
Adam J. Foxson
-
Adam Kennedy
-
Andy Jack
-
Anirvan Chatterjee
-
Ansgar Burchardt
-
A. Sinan Unur
-
Ben Hutton
-
Brendan Byrd
-
Chad Granum
-
Chankey Pathak
-
Chia-liang Kao
-
Christian Walde (Mithaldu)
-
chromatic
-
Dann
-
Dave Romano
-
David Leadbeater
-
David Steinbrunner
-
dmaestro
-
E. Choroba
-
franck cuny
-
Frew Schmidt
-
gregor herrmann
-
hakim
-
Henry Van Styn
-
James Marca
-
Jason May
-
Jay Allen
-
Jay Kuri
-
Jeff Bisbee
-
Jens Berthold
-
Jesse Vincent
-
joel
-
John Douglas Porter
-
John Goulah
-
Justin DeVuyst
-
Kang-min Liu
-
Leon Timmermans
-
Mark O Grady
-
Matt Kraai
-
Michael Schout
-
Nathan Gray
-
Olaf Alders
-
Olof Johansson
-
Paul Cochrane
-
Paweł Murias
-
Pedro Melo
-
Peter Shangov
-
Philippe Bruhat (BooK)
-
Philipp Gortan
-
Phillip Smith
-
Piotr Roszatycki
-
pktm
-
rouzier
-
Sam Vilain
-
sherrardb
-
Simon Reinhardt
-
sue spence
-
Tuomas Jormola
-
wickline
-
Yanick Champoux
-
Zoffix Znet
- Dependencies
- Carp
- Class::Load
- Class::Load::XS
- Data::OptList
- Devel::GlobalDestruction
- Devel::OverloadInfo
- Devel::StackTrace
- Dist::CheckConflicts
- Eval::Closure
- List::Util
- MRO::Compat
- Module::Runtime
- Module::Runtime::Conflicts
- Package::DeprecationManager
- Package::Stash
- Package::Stash::XS
- Params::Util
- Scalar::Util
- Sub::Exporter
- Sub::Util
- Try::Tiny
- parent
- strict
- warnings
- Reverse dependencies
- CPAN Testers List
- Dependency graph
- NAME
- VERSION
- WHERE'S THE CONSTRUCTOR?
- OBJECT CONSTRUCTION AND ATTRIBUTES
- OBJECT CONSTRUCTION HOOKS
- OBJECT DESTRUCTION
- AUTHORS
- COPYRIGHT AND LICENSE
NAME
Moose::Manual::Construction - Object construction (and destruction) with Moose
VERSION
version 2.2201
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 anew()
method for your class. If you follow our recommendations in Moose::Manual::BestPractices and make your class immutable, then you actually get a class-specificnew()
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_arg
s). 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/orBUILDARGS
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 tonew()
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_arg
s).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 theBUILDARGS
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 defaultBUILDARGS
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 aBUILD
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 byBUILDARGS
). 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 toBUILD
. Roles are an exception to this rule, though: it's completely acceptable to apply a method modifier toBUILD
in a role; you can even provide an emptyBUILD
subroutine in a role so the role is applicable even to classes without their ownBUILD
.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 specificBUILD
method first. Also, this is how Perl 6 does it.OBJECT DESTRUCTION
Moose provides a hook for object destruction with the
DEMOLISH
method. As withBUILD
, you should never explicitly call$self->SUPER::DEMOLISH
. Moose will arrange for all of theDEMOLISH
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 callexit
, that exit code will be preserved even if an object's destructor makes a system call.Moose also preserves
$@
against anyeval
calls that may happen during object destruction. However, if an object'sDEMOLISH
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.
Module Install Instructions
To install Moose, copy and paste the appropriate command in to your terminal.
cpanm Moose
perl -MCPAN -e shell install Moose
For more information on module installation, please visit the detailed CPAN module installation guide.