Merge ../Moose-error into pluggable_errors
[gitmo/Moose.git] / lib / Moose.pm
CommitLineData
fcd84ca9 1
2package Moose;
3
4use strict;
5use warnings;
6
e606ae5f 7use 5.008;
8
9our $VERSION = '0.57';
10$VERSION = eval $VERSION;
d44714be 11our $AUTHORITY = 'cpan:STEVAN';
fcd84ca9 12
21f1e231 13use Scalar::Util 'blessed';
c0b37457 14use Carp 'confess', 'croak', 'cluck';
fcd84ca9 15
e606ae5f 16use Moose::Exporter;
7f18097c 17
e606ae5f 18use Class::MOP 0.65;
ef1d5f4b 19
c0e30cf5 20use Moose::Meta::Class;
7415b2cb 21use Moose::Meta::TypeConstraint;
7c13858b 22use Moose::Meta::TypeCoercion;
78cd1d3b 23use Moose::Meta::Attribute;
ddd0ec20 24use Moose::Meta::Instance;
c0e30cf5 25
e606ae5f 26use Moose::Object;
27
d67145ed 28use Moose::Meta::Role;
e606ae5f 29use Moose::Meta::Role::Composite;
30use Moose::Meta::Role::Application;
31use Moose::Meta::Role::Application::RoleSummation;
32use Moose::Meta::Role::Application::ToClass;
33use Moose::Meta::Role::Application::ToRole;
34use Moose::Meta::Role::Application::ToInstance;
d67145ed 35
7415b2cb 36use Moose::Util::TypeConstraints;
d7d8a8c7 37use Moose::Util ();
a15dff8d 38
4c0b3599 39BEGIN { *throw_error = \&confess } # FIXME make this smarter
40
e606ae5f 41sub extends {
42 my $class = shift;
a3c7e2fe 43
e606ae5f 44 croak "Must derive at least one class" unless @_;
45
46 my @supers = @_;
47 foreach my $super (@supers) {
48 Class::MOP::load_class($super);
49 croak "You cannot inherit from a Moose Role ($super)"
50 if $super->can('meta') &&
51 blessed $super->meta &&
52 $super->meta->isa('Moose::Meta::Role')
a3c7e2fe 53 }
54
9bcfbab1 55
5bee491d 56
e606ae5f 57 # this checks the metaclass to make sure
58 # it is correct, sometimes it can get out
59 # of sync when the classes are being built
60 my $meta = Moose::Meta::Class->initialize($class)->_fix_metaclass_incompatability(@supers);
61 $meta->superclasses(@supers);
62}
26fbace8 63
e606ae5f 64sub with {
65 my $class = shift;
66 Moose::Util::apply_all_roles(Class::MOP::Class->initialize($class), @_);
67}
86dd5d11 68
e606ae5f 69sub has {
70 my $class = shift;
71 my $name = shift;
72 croak 'Usage: has \'name\' => ( key => value, ... )' if @_ == 1;
73 my %options = @_;
74 my $attrs = ( ref($name) eq 'ARRAY' ) ? $name : [ ($name) ];
75 Class::MOP::Class->initialize($class)->add_attribute( $_, %options ) for @$attrs;
76}
77
78sub before {
79 my $class = shift;
80 Moose::Util::add_method_modifier($class, 'before', \@_);
81}
a3c7e2fe 82
e606ae5f 83sub after {
84 my $class = shift;
85 Moose::Util::add_method_modifier($class, 'after', \@_);
86}
9bcfbab1 87
e606ae5f 88sub around {
89 my $class = shift;
90 Moose::Util::add_method_modifier($class, 'around', \@_);
91}
92
93sub super {
94 return unless our $SUPER_BODY; $SUPER_BODY->(our @SUPER_ARGS);
95}
9bcfbab1 96
e606ae5f 97sub override {
98 my $class = shift;
99 my ( $name, $method ) = @_;
100 Class::MOP::Class->initialize($class)->add_override_method_modifier( $name => $method );
101}
102
103sub inner {
104 my $pkg = caller();
105 our ( %INNER_BODY, %INNER_ARGS );
106
107 if ( my $body = $INNER_BODY{$pkg} ) {
108 my @args = @{ $INNER_ARGS{$pkg} };
109 local $INNER_ARGS{$pkg};
110 local $INNER_BODY{$pkg};
111 return $body->(@args);
112 } else {
113 return;
fcb7afc2 114 }
e606ae5f 115}
116
117sub augment {
118 my $class = shift;
119 my ( $name, $method ) = @_;
120 Class::MOP::Class->initialize($class)->add_augment_method_modifier( $name => $method );
121}
122
123sub make_immutable {
124 my $class = shift;
125 cluck "The make_immutable keyword has been deprecated, " .
126 "please go back to __PACKAGE__->meta->make_immutable\n";
127 Class::MOP::Class->initialize($class)->make_immutable(@_);
128}
129
130Moose::Exporter->setup_import_methods(
131 with_caller => [
132 qw( extends with has before after around override augment make_immutable )
133 ],
134 as_is => [
135 qw( super inner ),
136 \&Carp::confess,
137 \&Scalar::Util::blessed,
138 ],
139);
140
141sub init_meta {
142 # This used to be called as a function. This hack preserves
143 # backwards compatibility.
144 if ( $_[0] ne __PACKAGE__ ) {
145 return __PACKAGE__->init_meta(
146 for_class => $_[0],
147 base_class => $_[1],
148 metaclass => $_[2],
149 );
c01baab6 150 }
9bcfbab1 151
e606ae5f 152 shift;
153 my %args = @_;
154
155 my $class = $args{for_class}
4c0b3599 156 or throw_error "Cannot call init_meta without specifying a for_class";
e606ae5f 157 my $base_class = $args{base_class} || 'Moose::Object';
158 my $metaclass = $args{metaclass} || 'Moose::Meta::Class';
159
4c0b3599 160 throw_error
e606ae5f 161 "The Metaclass $metaclass must be a subclass of Moose::Meta::Class."
162 unless $metaclass->isa('Moose::Meta::Class');
9bcfbab1 163
e606ae5f 164 # make a subtype for each Moose class
165 class_type($class)
166 unless find_type_constraint($class);
167
168 my $meta;
169
170 if ( $meta = Class::MOP::get_metaclass_by_name($class) ) {
171 unless ( $meta->isa("Moose::Meta::Class") ) {
4c0b3599 172 throw_error "$class already has a metaclass, but it does not inherit $metaclass ($meta)";
e606ae5f 173 }
174 } else {
175 # no metaclass, no 'meta' method
9bcfbab1 176
e606ae5f 177 # now we check whether our ancestors have metaclass, and if so borrow that
178 my ( undef, @isa ) = @{ $class->mro::get_linear_isa };
9bcfbab1 179
e606ae5f 180 foreach my $ancestor ( @isa ) {
181 my $ancestor_meta = Class::MOP::get_metaclass_by_name($ancestor) || next;
9bcfbab1 182
e606ae5f 183 my $ancestor_meta_class = ($ancestor_meta->is_immutable
184 ? $ancestor_meta->get_mutable_metaclass_name
185 : ref($ancestor_meta));
186
187 # if we have an ancestor metaclass that inherits $metaclass, we use
188 # that. This is like _fix_metaclass_incompatability, but we can do it now.
189
190 # the case of having an ancestry is not very common, but arises in
191 # e.g. Reaction
192 unless ( $metaclass->isa( $ancestor_meta_class ) ) {
193 if ( $ancestor_meta_class->isa($metaclass) ) {
194 $metaclass = $ancestor_meta_class;
195 }
31f8ec72 196 }
197 }
e606ae5f 198
199 $meta = $metaclass->initialize($class);
200 }
201
202 if ( $class->can('meta') ) {
203 # check 'meta' method
204
205 # it may be inherited
206
207 # NOTE:
208 # this is the case where the metaclass pragma
209 # was used before the 'use Moose' statement to
210 # override a specific class
211 my $method_meta = $class->meta;
212
213 ( blessed($method_meta) && $method_meta->isa('Moose::Meta::Class') )
4c0b3599 214 || throw_error "$class already has a &meta function, but it does not return a Moose::Meta::Class ($meta)";
e606ae5f 215
216 $meta = $method_meta;
217 }
218
219 unless ( $meta->has_method("meta") ) { # don't overwrite
220 # also check for inherited non moose 'meta' method?
221 # FIXME also skip this if the user requested by passing an option
222 $meta->add_method(
223 'meta' => sub {
224 # re-initialize so it inherits properly
225 $metaclass->initialize( ref($_[0]) || $_[0] );
226 }
227 );
31f8ec72 228 }
9bcfbab1 229
e606ae5f 230 # make sure they inherit from Moose::Object
231 $meta->superclasses($base_class)
232 unless $meta->superclasses();
233
234 return $meta;
235}
236
237# This may be used in some older MooseX extensions.
238sub _get_caller {
239 goto &Moose::Exporter::_get_caller;
fcd84ca9 240}
241
8ecb1fa0 242## make 'em all immutable
243
244$_->meta->make_immutable(
e606ae5f 245 inline_constructor => 1,
246 constructor_name => "_new",
77a18c28 247 inline_accessors => 1, # these are Class::MOP accessors, so they need inlining
9bcfbab1 248 )
e606ae5f 249 for (qw(
250 Moose::Meta::Attribute
251 Moose::Meta::Class
252 Moose::Meta::Instance
253
254 Moose::Meta::TypeConstraint
255 Moose::Meta::TypeConstraint::Union
256 Moose::Meta::TypeConstraint::Parameterized
257 Moose::Meta::TypeConstraint::Parameterizable
258 Moose::Meta::TypeConstraint::Enum
259 Moose::Meta::TypeConstraint::Class
260 Moose::Meta::TypeConstraint::Role
261 Moose::Meta::TypeConstraint::Registry
262 Moose::Meta::TypeCoercion
263 Moose::Meta::TypeCoercion::Union
264
265 Moose::Meta::Method
266 Moose::Meta::Method::Accessor
267 Moose::Meta::Method::Constructor
268 Moose::Meta::Method::Destructor
269 Moose::Meta::Method::Overriden
270 Moose::Meta::Method::Augmented
271
272 Moose::Meta::Role
273 Moose::Meta::Role::Method
274 Moose::Meta::Role::Method::Required
275
276 Moose::Meta::Role::Composite
277
278 Moose::Meta::Role::Application
279 Moose::Meta::Role::Application::RoleSummation
280 Moose::Meta::Role::Application::ToClass
281 Moose::Meta::Role::Application::ToRole
282 Moose::Meta::Role::Application::ToInstance
283));
8ecb1fa0 284
fcd84ca9 2851;
286
287__END__
288
289=pod
290
291=head1 NAME
292
8bdc7f13 293Moose - A postmodern object system for Perl 5
fcd84ca9 294
295=head1 SYNOPSIS
e522431d 296
297 package Point;
1cd45431 298 use Moose; # automatically turns on strict and warnings
26fbace8 299
43d599e5 300 has 'x' => (is => 'rw', isa => 'Int');
301 has 'y' => (is => 'rw', isa => 'Int');
26fbace8 302
e522431d 303 sub clear {
304 my $self = shift;
305 $self->x(0);
26fbace8 306 $self->y(0);
e522431d 307 }
26fbace8 308
e522431d 309 package Point3D;
310 use Moose;
26fbace8 311
e522431d 312 extends 'Point';
26fbace8 313
43d599e5 314 has 'z' => (is => 'rw', isa => 'Int');
26fbace8 315
e522431d 316 after 'clear' => sub {
317 my $self = shift;
43d599e5 318 $self->z(0);
26fbace8 319 };
2c0cbef7 320
fcd84ca9 321=head1 DESCRIPTION
322
26fbace8 323Moose is an extension of the Perl 5 object system.
e522431d 324
9b9da6f1 325The main goal of Moose is to make Perl 5 Object Oriented programming
326easier, more consistent and less tedious. With Moose you can to think
e606ae5f 327more about what you want to do and less about the mechanics of OOP.
328
329Additionally, Moose is built on top of L<Class::MOP>, which is a
330metaclass system for Perl 5. This means that Moose not only makes
331building normal Perl 5 objects better, but it provides the power of
332metaclass programming as well.
333
334=head2 New to Moose?
fcd84ca9 335
e606ae5f 336If you're new to Moose, the best place to start is the L<Moose::Intro>
337docs, followed by the L<Moose::Cookbook>. The intro will show you what
338Moose is, and how it makes Perl 5 OO better.
339
340The cookbook recipes on Moose basics will get you up to speed with
341many of Moose's features quickly. Once you have an idea of what Moose
342can do, you can use the API documentation to get more detail on
343features which interest you.
8bdc7f13 344
28669f89 345=head2 Moose Extensions
346
e606ae5f 347The C<MooseX::> namespace is the official place to find Moose extensions.
348These extensions can be found on the CPAN. The easiest way to find them
349is to search for them (L<http://search.cpan.org/search?query=MooseX::>),
350or to examine L<Task::Moose> which aims to keep an up-to-date, easily
351installable list of Moose extensions.
28669f89 352
6ba6d68c 353=head1 BUILDING CLASSES WITH MOOSE
354
68efb014 355Moose makes every attempt to provide as much convenience as possible during
356class construction/definition, but still stay out of your way if you want it
357to. Here are a few items to note when building classes with Moose.
6ba6d68c 358
26fbace8 359Unless specified with C<extends>, any class which uses Moose will
6ba6d68c 360inherit from L<Moose::Object>.
361
1cd45431 362Moose will also manage all attributes (including inherited ones) that are
363defined with C<has>. And (assuming you call C<new>, which is inherited from
364L<Moose::Object>) this includes properly initializing all instance slots,
365setting defaults where appropriate, and performing any type constraint checking
366or coercion.
6ba6d68c 367
004222dc 368=head1 PROVIDED METHODS
6ba6d68c 369
004222dc 370Moose provides a number of methods to all your classes, mostly through the
371inheritance of L<Moose::Object>. There is however, one exception.
6ba6d68c 372
373=over 4
374
375=item B<meta>
376
377This is a method which provides access to the current class's metaclass.
378
004222dc 379=back
380
381=head1 EXPORTED FUNCTIONS
382
383Moose will export a number of functions into the class's namespace which
384may then be used to set up the class. These functions all work directly
385on the current class.
386
387=over 4
388
6ba6d68c 389=item B<extends (@superclasses)>
390
391This function will set the superclass(es) for the current class.
392
26fbace8 393This approach is recommended instead of C<use base>, because C<use base>
394actually C<push>es onto the class's C<@ISA>, whereas C<extends> will
395replace it. This is important to ensure that classes which do not have
68efb014 396superclasses still properly inherit from L<Moose::Object>.
6ba6d68c 397
43d599e5 398=item B<with (@roles)>
e9ec68d6 399
004222dc 400This will apply a given set of C<@roles> to the local class.
e9ec68d6 401
cd7eeaf5 402=item B<has $name =E<gt> %options>
6ba6d68c 403
26fbace8 404This will install an attribute of a given C<$name> into the current class.
405The C<%options> are the same as those provided by
406L<Class::MOP::Attribute>, in addition to the list below which are provided
43d599e5 407by Moose (L<Moose::Meta::Attribute> to be more specific):
6ba6d68c 408
409=over 4
410
076c81ed 411=item I<is =E<gt> 'rw'|'ro'>
6ba6d68c 412
26fbace8 413The I<is> option accepts either I<rw> (for read/write) or I<ro> (for read
414only). These will create either a read/write accessor or a read-only
6ba6d68c 415accessor respectively, using the same name as the C<$name> of the attribute.
416
1cd45431 417If you need more control over how your accessors are named, you can use the
418I<reader>, I<writer> and I<accessor> options inherited from
004222dc 419L<Class::MOP::Attribute>, however if you use those, you won't need the I<is>
420option.
6ba6d68c 421
076c81ed 422=item I<isa =E<gt> $type_name>
6ba6d68c 423
26fbace8 424The I<isa> option uses Moose's type constraint facilities to set up runtime
425type checking for this attribute. Moose will perform the checks during class
426construction, and within any accessors. The C<$type_name> argument must be a
427string. The string may be either a class name or a type defined using
9cca2e9e 428Moose's type definition features. (Refer to L<Moose::Util::TypeConstraints>
c2a69ef1 429for information on how to define a new type, and how to retrieve type meta-data).
6ba6d68c 430
daea75c9 431=item I<coerce =E<gt> (1|0)>
432
26fbace8 433This will attempt to use coercion with the supplied type constraint to change
434the value passed into any accessors or constructors. You B<must> have supplied
e606ae5f 435a type constraint in order for this to work. See L<Moose::Cookbook::Basics::Recipe5>
1cd45431 436for an example.
daea75c9 437
438=item I<does =E<gt> $role_name>
439
26fbace8 440This will accept the name of a role which the value stored in this attribute
daea75c9 441is expected to have consumed.
442
443=item I<required =E<gt> (1|0)>
444
26fbace8 445This marks the attribute as being required. This means a I<defined> value must be
446supplied during class construction, and the attribute may never be set to
447C<undef> with an accessor.
daea75c9 448
449=item I<weak_ref =E<gt> (1|0)>
450
68efb014 451This will tell the class to store the value of this attribute as a weakened
452reference. If an attribute is a weakened reference, it B<cannot> also be
453coerced.
daea75c9 454
455=item I<lazy =E<gt> (1|0)>
456
26fbace8 457This will tell the class to not create this slot until absolutely necessary.
daea75c9 458If an attribute is marked as lazy it B<must> have a default supplied.
459
9e93dd19 460=item I<auto_deref =E<gt> (1|0)>
461
26fbace8 462This tells the accessor whether to automatically dereference the value returned.
1cd45431 463This is only legal if your C<isa> option is either C<ArrayRef> or C<HashRef>.
9e93dd19 464
daea75c9 465=item I<trigger =E<gt> $code>
466
1cd45431 467The I<trigger> option is a CODE reference which will be called after the value of
468the attribute is set. The CODE ref will be passed the instance itself, the
daea75c9 469updated value and the attribute meta-object (this is for more advanced fiddling
1cd45431 470and can typically be ignored). You B<cannot> have a trigger on a read-only
471attribute.
daea75c9 472
c84f324f 473=item I<handles =E<gt> ARRAY | HASH | REGEXP | ROLE | CODE>
2c0cbef7 474
26fbace8 475The I<handles> option provides Moose classes with automated delegation features.
476This is a pretty complex and powerful option. It accepts many different option
477formats, each with its own benefits and drawbacks.
38e3283b 478
1cd45431 479B<NOTE:> The class being delegated to does not need to be a Moose based class,
480which is why this feature is especially useful when wrapping non-Moose classes.
38e3283b 481
1cd45431 482All I<handles> option formats share the following traits:
38e3283b 483
1cd45431 484You cannot override a locally defined method with a delegated method; an
485exception will be thrown if you try. That is to say, if you define C<foo> in
486your class, you cannot override it with a delegated C<foo>. This is almost never
487something you would want to do, and if it is, you should do it by hand and not
488use Moose.
38e3283b 489
1cd45431 490You cannot override any of the methods found in Moose::Object, or the C<BUILD>
491and C<DEMOLISH> methods. These will not throw an exception, but will silently
492move on to the next method in the list. My reasoning for this is that you would
493almost never want to do this, since it usually breaks your class. As with
494overriding locally defined methods, if you do want to do this, you should do it
495manually, not with Moose.
38e3283b 496
f3c4e20e 497You do not I<need> to have a reader (or accessor) for the attribute in order
498to delegate to it. Moose will create a means of accessing the value for you,
499however this will be several times B<less> efficient then if you had given
500the attribute a reader (or accessor) to use.
501
38e3283b 502Below is the documentation for each option format:
503
504=over 4
505
506=item C<ARRAY>
507
26fbace8 508This is the most common usage for I<handles>. You basically pass a list of
509method names to be delegated, and Moose will install a delegation method
1cd45431 510for each one.
38e3283b 511
512=item C<HASH>
513
26fbace8 514This is the second most common usage for I<handles>. Instead of a list of
515method names, you pass a HASH ref where each key is the method name you
516want installed locally, and its value is the name of the original method
517in the class being delegated to.
fd595040 518
26fbace8 519This can be very useful for recursive classes like trees. Here is a
e606ae5f 520quick example (soon to be expanded into a Moose::Cookbook recipe):
38e3283b 521
1cd45431 522 package Tree;
38e3283b 523 use Moose;
26fbace8 524
38e3283b 525 has 'node' => (is => 'rw', isa => 'Any');
26fbace8 526
38e3283b 527 has 'children' => (
528 is => 'ro',
529 isa => 'ArrayRef',
530 default => sub { [] }
531 );
26fbace8 532
38e3283b 533 has 'parent' => (
534 is => 'rw',
535 isa => 'Tree',
a4e516f6 536 weak_ref => 1,
38e3283b 537 handles => {
538 parent_node => 'node',
26fbace8 539 siblings => 'children',
38e3283b 540 }
541 );
542
1cd45431 543In this example, the Tree package gets C<parent_node> and C<siblings> methods,
544which delegate to the C<node> and C<children> methods (respectively) of the Tree
26fbace8 545instance stored in the C<parent> slot.
38e3283b 546
547=item C<REGEXP>
548
26fbace8 549The regexp option works very similar to the ARRAY option, except that it builds
550the list of methods for you. It starts by collecting all possible methods of the
551class being delegated to, then filters that list using the regexp supplied here.
38e3283b 552
26fbace8 553B<NOTE:> An I<isa> option is required when using the regexp option format. This
554is so that we can determine (at compile time) the method list from the class.
38e3283b 555Without an I<isa> this is just not possible.
556
c84f324f 557=item C<ROLE>
558
26fbace8 559With the role option, you specify the name of a role whose "interface" then
560becomes the list of methods to handle. The "interface" can be defined as; the
561methods of the role and any required methods of the role. It should be noted
562that this does B<not> include any method modifiers or generated attribute
c84f324f 563methods (which is consistent with role composition).
564
38e3283b 565=item C<CODE>
566
1cd45431 567This is the option to use when you really want to do something funky. You should
568only use it if you really know what you are doing, as it involves manual
569metaclass twiddling.
38e3283b 570
1cd45431 571This takes a code reference, which should expect two arguments. The first is the
572attribute meta-object this I<handles> is attached to. The second is the
573metaclass of the class being delegated to. It expects you to return a hash (not
26fbace8 574a HASH ref) of the methods you want mapped.
38e3283b 575
576=back
2c0cbef7 577
004222dc 578=item I<metaclass =E<gt> $metaclass_name>
579
580This tells the class to use a custom attribute metaclass for this particular
581attribute. Custom attribute metaclasses are useful for extending the
582capabilities of the I<has> keyword: they are the simplest way to extend the MOP,
583but they are still a fairly advanced topic and too much to cover here, see
e606ae5f 584L<Moose::Cookbook::Meta::Recipe1> for more information.
004222dc 585
586The default behavior here is to just load C<$metaclass_name>; however, we also
587have a way to alias to a shorter name. This will first look to see if
588B<Moose::Meta::Attribute::Custom::$metaclass_name> exists. If it does, Moose
589will then check to see if that has the method C<register_implementation>, which
590should return the actual name of the custom attribute metaclass. If there is no
591C<register_implementation> method, it will fall back to using
592B<Moose::Meta::Attribute::Custom::$metaclass_name> as the metaclass name.
593
594=item I<traits =E<gt> [ @role_names ]>
595
596This tells Moose to take the list of C<@role_names> and apply them to the
597attribute meta-object. This is very similar to the I<metaclass> option, but
e606ae5f 598allows you to use more than one extension at a time.
004222dc 599
e606ae5f 600See L<TRAIT NAME RESOLUTION> for details on how a trait name is
601resolved to a class name.
602
603Also see L<Moose::Cookbook::Meta::Recipe3> for a metaclass trait
604example.
004222dc 605
6ba6d68c 606=back
607
cd7eeaf5 608=item B<has +$name =E<gt> %options>
609
26fbace8 610This is variation on the normal attibute creator C<has> which allows you to
8d62bf6d 611clone and extend an attribute from a superclass or from a role. Here is an
612example of the superclass usage:
cd7eeaf5 613
614 package Foo;
615 use Moose;
26fbace8 616
cd7eeaf5 617 has 'message' => (
26fbace8 618 is => 'rw',
cd7eeaf5 619 isa => 'Str',
620 default => 'Hello, I am a Foo'
621 );
26fbace8 622
cd7eeaf5 623 package My::Foo;
624 use Moose;
26fbace8 625
cd7eeaf5 626 extends 'Foo';
26fbace8 627
cd7eeaf5 628 has '+message' => (default => 'Hello I am My::Foo');
629
1cd45431 630What is happening here is that B<My::Foo> is cloning the C<message> attribute
631from its parent class B<Foo>, retaining the C<is =E<gt> 'rw'> and C<isa =E<gt>
632'Str'> characteristics, but changing the value in C<default>.
cd7eeaf5 633
8d62bf6d 634Here is another example, but within the context of a role:
635
636 package Foo::Role;
637 use Moose::Role;
e606ae5f 638
8d62bf6d 639 has 'message' => (
640 is => 'rw',
641 isa => 'Str',
642 default => 'Hello, I am a Foo'
643 );
e606ae5f 644
8d62bf6d 645 package My::Foo;
646 use Moose;
e606ae5f 647
8d62bf6d 648 with 'Foo::Role';
e606ae5f 649
8d62bf6d 650 has '+message' => (default => 'Hello I am My::Foo');
651
652In this case, we are basically taking the attribute which the role supplied
4032c9bb 653and altering it within the bounds of this feature.
8d62bf6d 654
4032c9bb 655Aside from where the attributes come from (one from superclass, the other
656from a role), this feature works exactly the same. This feature is restricted
657somewhat, so as to try and force at least I<some> sanity into it. You are only
658allowed to change the following attributes:
cd7eeaf5 659
660=over 4
661
26fbace8 662=item I<default>
cd7eeaf5 663
664Change the default value of an attribute.
665
26fbace8 666=item I<coerce>
cd7eeaf5 667
668Change whether the attribute attempts to coerce a value passed to it.
669
26fbace8 670=item I<required>
cd7eeaf5 671
672Change if the attribute is required to have a value.
673
674=item I<documentation>
675
676Change the documentation string associated with the attribute.
677
83cc9094 678=item I<lazy>
679
680Change if the attribute lazily initializes the slot.
681
cd7eeaf5 682=item I<isa>
683
aed87761 684You I<are> allowed to change the type without restriction.
685
686It is recommended that you use this freedom with caution. We used to
687only allow for extension only if the type was a subtype of the parent's
688type, but we felt that was too restrictive and is better left as a
689policy descision.
cd7eeaf5 690
83cc9094 691=item I<handles>
692
26fbace8 693You are allowed to B<add> a new C<handles> definition, but you are B<not>
694allowed to I<change> one.
83cc9094 695
8d62bf6d 696=item I<builder>
697
698You are allowed to B<add> a new C<builder> definition, but you are B<not>
699allowed to I<change> one.
700
13284479 701=item I<metaclass>
702
703You are allowed to B<add> a new C<metaclass> definition, but you are
704B<not> allowed to I<change> one.
705
706=item I<traits>
707
708You are allowed to B<add> additional traits to the C<traits> definition.
709These traits will be composed into the attribute, but pre-existing traits
710B<are not> overridden, or removed.
711
cd7eeaf5 712=back
713
076c81ed 714=item B<before $name|@names =E<gt> sub { ... }>
6ba6d68c 715
076c81ed 716=item B<after $name|@names =E<gt> sub { ... }>
6ba6d68c 717
076c81ed 718=item B<around $name|@names =E<gt> sub { ... }>
6ba6d68c 719
d8af92ae 720This three items are syntactic sugar for the before, after, and around method
721modifier features that L<Class::MOP> provides. More information on these may be
722found in the L<Class::MOP::Class documentation|Class::MOP::Class/"Method
723Modifiers"> for now.
6ba6d68c 724
159da176 725=item B<super>
726
26fbace8 727The keyword C<super> is a no-op when called outside of an C<override> method. In
728the context of an C<override> method, it will call the next most appropriate
159da176 729superclass method with the same arguments as the original method.
730
731=item B<override ($name, &sub)>
732
26fbace8 733An C<override> method is a way of explicitly saying "I am overriding this
734method from my superclass". You can call C<super> within this method, and
735it will work as expected. The same thing I<can> be accomplished with a normal
736method call and the C<SUPER::> pseudo-package; it is really your choice.
159da176 737
738=item B<inner>
739
26fbace8 740The keyword C<inner>, much like C<super>, is a no-op outside of the context of
741an C<augment> method. You can think of C<inner> as being the inverse of
68efb014 742C<super>; the details of how C<inner> and C<augment> work is best described in
e606ae5f 743the L<Moose::Cookbook::Basics::Recipe6>.
159da176 744
745=item B<augment ($name, &sub)>
746
26fbace8 747An C<augment> method, is a way of explicitly saying "I am augmenting this
748method from my superclass". Once again, the details of how C<inner> and
e606ae5f 749C<augment> work is best described in the L<Moose::Cookbook::Basics::Recipe6>.
159da176 750
6ba6d68c 751=item B<confess>
752
68efb014 753This is the C<Carp::confess> function, and exported here because I use it
004222dc 754all the time.
6ba6d68c 755
756=item B<blessed>
757
1cd45431 758This is the C<Scalar::Util::blessed> function, it is exported here because I
26fbace8 759use it all the time. It is highly recommended that this is used instead of
6ba6d68c 760C<ref> anywhere you need to test for an object's class name.
761
762=back
763
e606ae5f 764=head1 METACLASS TRAITS
765
766When you use Moose, you can also specify traits which will be applied
767to your metaclass:
768
769 use Moose -traits => 'My::Trait';
770
771This is very similar to the attribute traits feature. When you do
772this, your class's C<meta> object will have the specified traits
773applied to it. See L<TRAIT NAME RESOLUTION> for more details.
774
775=head1 TRAIT NAME RESOLUTION
776
777By default, when given a trait name, Moose simply tries to load a
778class of the same name. If such a class does not exist, it then looks
779for for a class matching
780B<Moose::Meta::$type::Custom::Trait::$trait_name>. The C<$type>
781variable here will be one of B<Attribute> or B<Class>, depending on
782what the trait is being applied to.
783
784If a class with this long name exists, Moose checks to see if it has
785the method C<register_implementation>. This method is expected to
786return the I<real> class name of the trait. If there is no
787C<register_implementation> method, it will fall back to using
788B<Moose::Meta::$type::Custom::Trait::$trait> as the trait name.
789
790If all this is confusing, take a look at
791L<Moose::Cookbook::Meta::Recipe3>, which demonstrates how to create an
792attribute trait.
793
1cd45431 794=head1 UNIMPORTING FUNCTIONS
31f8ec72 795
796=head2 B<unimport>
797
1cd45431 798Moose offers a way to remove the keywords it exports, through the C<unimport>
31f8ec72 799method. You simply have to say C<no Moose> at the bottom of your code for this
800to work. Here is an example:
801
802 package Person;
803 use Moose;
804
805 has 'first_name' => (is => 'rw', isa => 'Str');
806 has 'last_name' => (is => 'rw', isa => 'Str');
26fbace8 807
808 sub full_name {
31f8ec72 809 my $self = shift;
26fbace8 810 $self->first_name . ' ' . $self->last_name
31f8ec72 811 }
26fbace8 812
813 no Moose; # keywords are removed from the Person package
31f8ec72 814
9bcfbab1 815=head1 EXTENDING AND EMBEDDING MOOSE
816
e606ae5f 817Moose also offers some options for extending or embedding it into your
818own framework. To learn more about extending Moose, we recommend
819checking out the "Extending" recipes in the L<Moose::Cookbook>,
820starting with L<Moose::Cookbook::Extending::Recipe1>, which provides
821an overview of all the different ways you might extend Moose.
9bcfbab1 822
e606ae5f 823=head2 B<< Moose->init_meta(for_class => $class, base_class => $baseclass, metaclass => $metaclass) >>
26fbace8 824
e606ae5f 825The C<init_meta> method sets up the metaclass object for the class
826specified by C<for_class>. This method injects a a C<meta> accessor
827into the class so you can get at this object. It also sets the class's
828superclass to C<base_class>, with L<Moose::Object> as the default.
9bcfbab1 829
e606ae5f 830You can specify an alternate metaclass with the C<metaclass> parameter.
9bcfbab1 831
e606ae5f 832For more detail on this topic, see L<Moose::Cookbook::Extending::Recipe2>.
9bcfbab1 833
e606ae5f 834This method used to be documented as a function which accepted
835positional parameters. This calling style will still work for
836backwards compatibility, but is deprecated.
26fbace8 837
9bcfbab1 838=head2 B<import>
839
77a18c28 840Moose's C<import> method supports the L<Sub::Exporter> form of C<{into =E<gt> $pkg}>
e606ae5f 841and C<{into_level =E<gt> 1}>.
9bcfbab1 842
e606ae5f 843B<NOTE>: Doing this is more or less deprecated. Use L<Moose::Exporter>
844instead, which lets you stack multiple C<Moose.pm>-alike modules
845sanely. It handles getting the exported functions into the right place
846for you.
26fbace8 847
4c0b3599 848=head2 throw_error
849
850An alias for C<confess>, used by internally by Moose.
851
05d9eaf6 852=head1 CAVEATS
853
854=over 4
855
856=item *
857
1cd45431 858It should be noted that C<super> and C<inner> B<cannot> be used in the same
859method. However, they may be combined within the same class hierarchy; see
860F<t/014_override_augment_inner_super.t> for an example.
05d9eaf6 861
26fbace8 862The reason for this is that C<super> is only valid within a method
863with the C<override> modifier, and C<inner> will never be valid within an
864C<override> method. In fact, C<augment> will skip over any C<override> methods
68efb014 865when searching for its appropriate C<inner>.
05d9eaf6 866
1cd45431 867This might seem like a restriction, but I am of the opinion that keeping these
868two features separate (yet interoperable) actually makes them easy to use, since
869their behavior is then easier to predict. Time will tell whether I am right or
c84f324f 870not (UPDATE: so far so good).
05d9eaf6 871
9b9da6f1 872=back
873
5569c072 874=head1 ACKNOWLEDGEMENTS
875
876=over 4
877
54c189df 878=item I blame Sam Vilain for introducing me to the insanity that is meta-models.
5569c072 879
54c189df 880=item I blame Audrey Tang for then encouraging my meta-model habit in #perl6.
5569c072 881
26fbace8 882=item Without Yuval "nothingmuch" Kogman this module would not be possible,
54c189df 883and it certainly wouldn't have this name ;P
5569c072 884
26fbace8 885=item The basis of the TypeContraints module was Rob Kinyon's idea
5569c072 886originally, I just ran with it.
887
638585e1 888=item Thanks to mst & chansen and the whole #moose posse for all the
c84f324f 889early ideas/feature-requests/encouragement/bug-finding.
d46a48f3 890
68efb014 891=item Thanks to David "Theory" Wheeler for meta-discussions and spelling fixes.
892
5569c072 893=back
894
e90c03d0 895=head1 SEE ALSO
896
897=over 4
898
c84f324f 899=item L<http://www.iinteractive.com/moose>
900
901This is the official web home of Moose, it contains links to our public SVN repo
26fbace8 902as well as links to a number of talks and articles on Moose and Moose related
903technologies.
c84f324f 904
e606ae5f 905=item L<Moose::Cookbook> - How to cook a Moose
906
907=item The Moose is flying, a tutorial by Randal Schwartz
908
909Part 1 - L<http://www.stonehenge.com/merlyn/LinuxMag/col94.html>
910
911Part 2 - L<http://www.stonehenge.com/merlyn/LinuxMag/col95.html>
912
6ba6d68c 913=item L<Class::MOP> documentation
914
915=item The #moose channel on irc.perl.org
916
e67a0fca 917=item The Moose mailing list - moose@perl.org
918
9e0361e1 919=item Moose stats on ohloh.net - L<http://www.ohloh.net/projects/moose>
c84f324f 920
e606ae5f 921=item Several Moose extension modules in the C<MooseX::> namespace.
922
923See L<http://search.cpan.org/search?query=MooseX::> for extensions.
28669f89 924
c84f324f 925=back
926
004222dc 927=head2 Books
928
929=over 4
930
931=item The Art of the MetaObject Protocol
932
933I mention this in the L<Class::MOP> docs too, this book was critical in
934the development of both modules and is highly recommended.
935
936=back
937
26fbace8 938=head2 Papers
c84f324f 939
940=over 4
e90c03d0 941
159da176 942=item L<http://www.cs.utah.edu/plt/publications/oopsla04-gff.pdf>
943
26fbace8 944This paper (suggested by lbr on #moose) was what lead to the implementation
945of the C<super>/C<override> and C<inner>/C<augment> features. If you really
1cd45431 946want to understand them, I suggest you read this.
159da176 947
e90c03d0 948=back
949
fcd84ca9 950=head1 BUGS
951
26fbace8 952All complex software has bugs lurking in it, and this module is no
fcd84ca9 953exception. If you find a bug please either email me, or add the bug
954to cpan-RT.
955
e606ae5f 956=head1 FEATURE REQUESTS
957
958We are very strict about what features we add to the Moose core, especially
959the user-visible features. Instead we have made sure that the underlying
960meta-system of Moose is as extensible as possible so that you can add your
961own features easily. That said, occasionally there is a feature needed in the
962meta-system to support your planned extension, in which case you should
963either email the mailing list or join us on irc at #moose to discuss.
964
fcd84ca9 965=head1 AUTHOR
966
967Stevan Little E<lt>stevan@iinteractive.comE<gt>
968
9af1d28b 969B<with contributions from:>
db1ab48d 970
9af1d28b 971Aankhen
972
973Adam (Alias) Kennedy
974
975Anders (Debolaz) Nor Berle
976
5868294f 977Nathan (kolibre) Gray
978
9af1d28b 979Christian (chansen) Hansen
980
e7f8d0c2 981Hans Dieter (confound) Pearcey
982
9af1d28b 983Eric (ewilhelm) Wilhelm
984
985Guillermo (groditi) Roditi
986
987Jess (castaway) Robinson
988
989Matt (mst) Trout
990
991Robert (phaylon) Sedlacek
992
993Robert (rlb3) Boone
994
995Scott (konobi) McWhirter
996
f44ae52f 997Shlomi (rindolf) Fish
998
9af1d28b 999Yuval (nothingmuch) Kogman
1000
cbe25729 1001Chris (perigrin) Prather
1002
e606ae5f 1003Wallace (wreis) Reis
1004
e46f5cc2 1005Jonathan (jrockway) Rockway
1006
e606ae5f 1007Dave (autarch) Rolsky
1008
3ccdc84a 1009Piotr (dexter) Roszatycki
1010
26fbace8 1011Sam (mugwump) Vilain
f1917f58 1012
ac211120 1013Shawn (sartak) Moore
1014
9af1d28b 1015... and many other #moose folks
98aae381 1016
fcd84ca9 1017=head1 COPYRIGHT AND LICENSE
1018
778db3ac 1019Copyright 2006-2008 by Infinity Interactive, Inc.
fcd84ca9 1020
1021L<http://www.iinteractive.com>
1022
1023This library is free software; you can redistribute it and/or modify
26fbace8 1024it under the same terms as Perl itself.
fcd84ca9 1025
ddd0ec20 1026=cut