Clarify that coerce requires a TC with a coercion
[gitmo/Moose.git] / lib / Moose.pm
CommitLineData
fcd84ca9 1package Moose;
d1e17c7f 2use strict;
3use warnings;
fcd84ca9 4
ecb1297a 5use 5.008;
6
55d05fb1 7our $VERSION = '1.12';
75b95414 8$VERSION = eval $VERSION;
d44714be 9our $AUTHORITY = 'cpan:STEVAN';
fcd84ca9 10
21f1e231 11use Scalar::Util 'blessed';
e2095e4a 12use Carp 'confess';
fcd84ca9 13
1fa1a58d 14use Moose::Deprecated;
5bd4db9b 15use Moose::Exporter;
7f18097c 16
88f6146f 17use Class::MOP 1.05;
ef1d5f4b 18
c0e30cf5 19use Moose::Meta::Class;
7415b2cb 20use Moose::Meta::TypeConstraint;
7c13858b 21use Moose::Meta::TypeCoercion;
78cd1d3b 22use Moose::Meta::Attribute;
ddd0ec20 23use Moose::Meta::Instance;
c0e30cf5 24
0779da92 25use Moose::Object;
26
d67145ed 27use Moose::Meta::Role;
0779da92 28use Moose::Meta::Role::Composite;
29use Moose::Meta::Role::Application;
30use Moose::Meta::Role::Application::RoleSummation;
31use Moose::Meta::Role::Application::ToClass;
32use Moose::Meta::Role::Application::ToRole;
33use Moose::Meta::Role::Application::ToInstance;
d67145ed 34
7415b2cb 35use Moose::Util::TypeConstraints;
d7d8a8c7 36use Moose::Util ();
a15dff8d 37
17e5e226 38use Moose::Meta::Attribute::Native;
fafc8b9b 39
c245d69b 40sub throw_error {
d03bd989 41 # FIXME This
c245d69b 42 shift;
43 goto \&confess
44}
4c0b3599 45
5bd4db9b 46sub extends {
d5447d26 47 my $meta = shift;
3d544ed5 48
e2095e4a 49 Moose->throw_error("Must derive at least one class") unless @_;
9bcfbab1 50
5bd4db9b 51 # this checks the metaclass to make sure
52 # it is correct, sometimes it can get out
53 # of sync when the classes are being built
d5447d26 54 $meta->superclasses(@_);
5bd4db9b 55}
a3c7e2fe 56
5bd4db9b 57sub with {
d5447d26 58 Moose::Util::apply_all_roles(shift, @_);
5bd4db9b 59}
9bcfbab1 60
5bd4db9b 61sub has {
d5447d26 62 my $meta = shift;
63 my $name = shift;
e2095e4a 64
65 Moose->throw_error('Usage: has \'name\' => ( key => value, ... )')
db532c7d 66 if @_ % 2 == 1;
e2095e4a 67
833b56a7 68 my %options = ( definition_context => Moose::Util::_caller_info(), @_ );
5bd4db9b 69 my $attrs = ( ref($name) eq 'ARRAY' ) ? $name : [ ($name) ];
d5447d26 70 $meta->add_attribute( $_, %options ) for @$attrs;
5bd4db9b 71}
9bcfbab1 72
5bd4db9b 73sub before {
d5447d26 74 Moose::Util::add_method_modifier(shift, 'before', \@_);
5bd4db9b 75}
76
77sub after {
d5447d26 78 Moose::Util::add_method_modifier(shift, 'after', \@_);
5bd4db9b 79}
80
81sub around {
d5447d26 82 Moose::Util::add_method_modifier(shift, 'around', \@_);
5bd4db9b 83}
84
991933fb 85our $SUPER_PACKAGE;
86our $SUPER_BODY;
87our @SUPER_ARGS;
88
5bd4db9b 89sub super {
991933fb 90 # This check avoids a recursion loop - see
91 # t/100_bugs/020_super_recursion.t
92 return if defined $SUPER_PACKAGE && $SUPER_PACKAGE ne caller();
93 return unless $SUPER_BODY; $SUPER_BODY->(@SUPER_ARGS);
5bd4db9b 94}
9bcfbab1 95
5bd4db9b 96sub override {
d5447d26 97 my $meta = shift;
5bd4db9b 98 my ( $name, $method ) = @_;
d5447d26 99 $meta->add_override_method_modifier( $name => $method );
5bd4db9b 100}
9bcfbab1 101
5bd4db9b 102sub inner {
103 my $pkg = caller();
104 our ( %INNER_BODY, %INNER_ARGS );
105
106 if ( my $body = $INNER_BODY{$pkg} ) {
107 my @args = @{ $INNER_ARGS{$pkg} };
108 local $INNER_ARGS{$pkg};
109 local $INNER_BODY{$pkg};
110 return $body->(@args);
111 } else {
112 return;
ce265cc3 113 }
5bd4db9b 114}
9bcfbab1 115
5bd4db9b 116sub augment {
d5447d26 117 my $meta = shift;
5bd4db9b 118 my ( $name, $method ) = @_;
d5447d26 119 $meta->add_augment_method_modifier( $name => $method );
ce265cc3 120}
9bcfbab1 121
aedcb7d9 122Moose::Exporter->setup_import_methods(
d5447d26 123 with_meta => [
348715c4 124 qw( extends with has before after around override augment )
97a93056 125 ],
126 as_is => [
127 qw( super inner ),
5bd4db9b 128 \&Carp::confess,
129 \&Scalar::Util::blessed,
130 ],
131);
132
cc841c0e 133sub init_meta {
085fba61 134 # This used to be called as a function. This hack preserves
135 # backwards compatibility.
136 if ( $_[0] ne __PACKAGE__ ) {
d69a348e 137 Moose::Deprecated::deprecated(
138 feature => 'Moose::init_meta',
139 message => 'Calling Moose::init_meta as a function is deprecated',
140 );
141
085fba61 142 return __PACKAGE__->init_meta(
143 for_class => $_[0],
144 base_class => $_[1],
145 metaclass => $_[2],
146 );
147 }
7c4676ef 148
0338a411 149 shift;
150 my %args = @_;
151
152 my $class = $args{for_class}
c245d69b 153 or Moose->throw_error("Cannot call init_meta without specifying a for_class");
085fba61 154 my $base_class = $args{base_class} || 'Moose::Object';
155 my $metaclass = $args{metaclass} || 'Moose::Meta::Class';
cc841c0e 156
c245d69b 157 Moose->throw_error("The Metaclass $metaclass must be a subclass of Moose::Meta::Class.")
cc841c0e 158 unless $metaclass->isa('Moose::Meta::Class');
159
160 # make a subtype for each Moose class
161 class_type($class)
162 unless find_type_constraint($class);
163
164 my $meta;
50d5df60 165
166 if ( $meta = Class::MOP::get_metaclass_by_name($class) ) {
167 unless ( $meta->isa("Moose::Meta::Class") ) {
677eafe2 168 my $error_message = "$class already has a metaclass, but it does not inherit $metaclass ($meta).";
169 if ( $meta->isa('Moose::Meta::Role') ) {
170 Moose->throw_error($error_message . ' You cannot make the same thing a role and a class. Remove either Moose or Moose::Role.');
171 } else {
172 Moose->throw_error($error_message);
173 }
50d5df60 174 }
175 } else {
176 # no metaclass, no 'meta' method
177
178 # now we check whether our ancestors have metaclass, and if so borrow that
72825dcd 179 my ( undef, @isa ) = @{ mro::get_linear_isa($class) };
50d5df60 180
181 foreach my $ancestor ( @isa ) {
182 my $ancestor_meta = Class::MOP::get_metaclass_by_name($ancestor) || next;
183
184 my $ancestor_meta_class = ($ancestor_meta->is_immutable
989263ad 185 ? $ancestor_meta->_get_mutable_metaclass_name
50d5df60 186 : ref($ancestor_meta));
187
188 # if we have an ancestor metaclass that inherits $metaclass, we use
41419b9e 189 # that. This is like _fix_metaclass_incompatibility, but we can do it now.
50d5df60 190
191 # the case of having an ancestry is not very common, but arises in
192 # e.g. Reaction
193 unless ( $metaclass->isa( $ancestor_meta_class ) ) {
194 if ( $ancestor_meta_class->isa($metaclass) ) {
195 $metaclass = $ancestor_meta_class;
196 }
197 }
198 }
199
200 $meta = $metaclass->initialize($class);
201 }
202
cc841c0e 203 if ( $class->can('meta') ) {
50d5df60 204 # check 'meta' method
205
206 # it may be inherited
207
cc841c0e 208 # NOTE:
209 # this is the case where the metaclass pragma
210 # was used before the 'use Moose' statement to
211 # override a specific class
50d5df60 212 my $method_meta = $class->meta;
213
214 ( blessed($method_meta) && $method_meta->isa('Moose::Meta::Class') )
e7e9a4d8 215 || Moose->throw_error("$class already has a &meta function, but it does not return a Moose::Meta::Class ($method_meta)");
50d5df60 216
217 $meta = $method_meta;
cc841c0e 218 }
50d5df60 219
220 unless ( $meta->has_method("meta") ) { # don't overwrite
221 # also check for inherited non moose 'meta' method?
222 # FIXME also skip this if the user requested by passing an option
cc841c0e 223 $meta->add_method(
224 'meta' => sub {
225 # re-initialize so it inherits properly
50d5df60 226 $metaclass->initialize( ref($_[0]) || $_[0] );
cc841c0e 227 }
228 );
229 }
230
231 # make sure they inherit from Moose::Object
232 $meta->superclasses($base_class)
233 unless $meta->superclasses();
234
235 return $meta;
236}
237
085fba61 238# This may be used in some older MooseX extensions.
239sub _get_caller {
240 goto &Moose::Exporter::_get_caller;
241}
242
8ecb1fa0 243## make 'em all immutable
244
3cae4250 245$_->make_immutable(
0779da92 246 inline_constructor => 1,
247 constructor_name => "_new",
3cae4250 248 # these are Class::MOP accessors, so they need inlining
249 inline_accessors => 1
250 ) for grep { $_->is_mutable }
251 map { $_->meta }
252 qw(
0779da92 253 Moose::Meta::Attribute
254 Moose::Meta::Class
255 Moose::Meta::Instance
256
0779da92 257 Moose::Meta::TypeCoercion
258 Moose::Meta::TypeCoercion::Union
259
260 Moose::Meta::Method
261 Moose::Meta::Method::Accessor
262 Moose::Meta::Method::Constructor
263 Moose::Meta::Method::Destructor
74862722 264 Moose::Meta::Method::Overridden
0779da92 265 Moose::Meta::Method::Augmented
266
267 Moose::Meta::Role
f785aad8 268 Moose::Meta::Role::Attribute
0779da92 269 Moose::Meta::Role::Method
270 Moose::Meta::Role::Method::Required
bb153262 271 Moose::Meta::Role::Method::Conflicting
0779da92 272
273 Moose::Meta::Role::Composite
274
275 Moose::Meta::Role::Application
276 Moose::Meta::Role::Application::RoleSummation
277 Moose::Meta::Role::Application::ToClass
278 Moose::Meta::Role::Application::ToRole
279 Moose::Meta::Role::Application::ToInstance
3cae4250 280);
8ecb1fa0 281
f785aad8 282Moose::Meta::Mixin::AttributeCore->meta->make_immutable(
283 inline_constructor => 0,
284 constructor_name => undef,
285);
286
fcd84ca9 2871;
288
289__END__
290
291=pod
292
293=head1 NAME
294
8bdc7f13 295Moose - A postmodern object system for Perl 5
fcd84ca9 296
297=head1 SYNOPSIS
e522431d 298
299 package Point;
1cd45431 300 use Moose; # automatically turns on strict and warnings
26fbace8 301
43d599e5 302 has 'x' => (is => 'rw', isa => 'Int');
303 has 'y' => (is => 'rw', isa => 'Int');
26fbace8 304
e522431d 305 sub clear {
306 my $self = shift;
307 $self->x(0);
26fbace8 308 $self->y(0);
e522431d 309 }
26fbace8 310
e522431d 311 package Point3D;
312 use Moose;
26fbace8 313
e522431d 314 extends 'Point';
26fbace8 315
43d599e5 316 has 'z' => (is => 'rw', isa => 'Int');
26fbace8 317
e522431d 318 after 'clear' => sub {
319 my $self = shift;
43d599e5 320 $self->z(0);
26fbace8 321 };
2c0cbef7 322
fcd84ca9 323=head1 DESCRIPTION
324
26fbace8 325Moose is an extension of the Perl 5 object system.
e522431d 326
9b9da6f1 327The main goal of Moose is to make Perl 5 Object Oriented programming
328easier, more consistent and less tedious. With Moose you can to think
6f894f30 329more about what you want to do and less about the mechanics of OOP.
fcd84ca9 330
6f894f30 331Additionally, Moose is built on top of L<Class::MOP>, which is a
332metaclass system for Perl 5. This means that Moose not only makes
333building normal Perl 5 objects better, but it provides the power of
334metaclass programming as well.
8bdc7f13 335
f5909dca 336=head2 New to Moose?
337
60eccd1e 338If you're new to Moose, the best place to start is the
339L<Moose::Manual> docs, followed by the L<Moose::Cookbook>. The intro
340will show you what Moose is, and how it makes Perl 5 OO better.
6f894f30 341
342The cookbook recipes on Moose basics will get you up to speed with
343many of Moose's features quickly. Once you have an idea of what Moose
344can do, you can use the API documentation to get more detail on
345features which interest you.
f5909dca 346
28669f89 347=head2 Moose Extensions
348
12aed9a0 349The C<MooseX::> namespace is the official place to find Moose extensions.
350These extensions can be found on the CPAN. The easiest way to find them
351is to search for them (L<http://search.cpan.org/search?query=MooseX::>),
352or to examine L<Task::Moose> which aims to keep an up-to-date, easily
353installable list of Moose extensions.
28669f89 354
ceb61b4f 355=head1 TRANSLATIONS
356
357Much of the Moose documentation has been translated into other languages.
358
359=over 4
360
52a0d29a 361=item Japanese
362
45902e41 363Japanese docs can be found at
364L<http://perldoc.perlassociation.org/pod/Moose-Doc-JA/index.html>. The
365source POD files can be found in GitHub:
366L<http://github.com/jpa/Moose-Doc-JA>
ceb61b4f 367
368=back
369
6ba6d68c 370=head1 BUILDING CLASSES WITH MOOSE
371
68efb014 372Moose makes every attempt to provide as much convenience as possible during
373class construction/definition, but still stay out of your way if you want it
374to. Here are a few items to note when building classes with Moose.
6ba6d68c 375
a6ae85e9 376When you C<use Moose>, Moose will set the class's parent class to
377L<Moose::Object>, I<unless> the class using Moose already has a parent
378class. In addition, specifying a parent with C<extends> will change the parent
379class.
6ba6d68c 380
1cd45431 381Moose will also manage all attributes (including inherited ones) that are
382defined with C<has>. And (assuming you call C<new>, which is inherited from
383L<Moose::Object>) this includes properly initializing all instance slots,
384setting defaults where appropriate, and performing any type constraint checking
385or coercion.
6ba6d68c 386
004222dc 387=head1 PROVIDED METHODS
6ba6d68c 388
d03bd989 389Moose provides a number of methods to all your classes, mostly through the
004222dc 390inheritance of L<Moose::Object>. There is however, one exception.
6ba6d68c 391
392=over 4
393
394=item B<meta>
395
396This is a method which provides access to the current class's metaclass.
397
004222dc 398=back
399
400=head1 EXPORTED FUNCTIONS
401
402Moose will export a number of functions into the class's namespace which
403may then be used to set up the class. These functions all work directly
404on the current class.
405
406=over 4
407
6ba6d68c 408=item B<extends (@superclasses)>
409
410This function will set the superclass(es) for the current class.
411
26fbace8 412This approach is recommended instead of C<use base>, because C<use base>
413actually C<push>es onto the class's C<@ISA>, whereas C<extends> will
414replace it. This is important to ensure that classes which do not have
68efb014 415superclasses still properly inherit from L<Moose::Object>.
6ba6d68c 416
2e7f6cf4 417Each superclass can be followed by a hash reference with options. Currently,
418only L<-version|Class::MOP/Class Loading Options> is recognized:
419
420 extends 'My::Parent' => { -version => 0.01 },
421 'My::OtherParent' => { -version => 0.03 };
422
423An exception will be thrown if the version requirements are not
424satisfied.
425
43d599e5 426=item B<with (@roles)>
e9ec68d6 427
d03bd989 428This will apply a given set of C<@roles> to the local class.
e9ec68d6 429
2e7f6cf4 430Like with C<extends>, each specified role can be followed by a hash
431reference with a L<-version|Class::MOP/Class Loading Options> option:
432
433 with 'My::Role' => { -version => 0.32 },
434 'My::Otherrole' => { -version => 0.23 };
435
436The specified version requirements must be satisfied, otherwise an
437exception will be thrown.
438
439If your role takes options or arguments, they can be passed along in the
440hash reference as well.
441
b4291ab4 442=item B<has $name|@$names =E<gt> %options>
6ba6d68c 443
b4291ab4 444This will install an attribute of a given C<$name> into the current class. If
445the first parameter is an array reference, it will create an attribute for
446every C<$name> in the list. The C<%options> are the same as those provided by
447L<Class::MOP::Attribute>, in addition to the list below which are provided by
448Moose (L<Moose::Meta::Attribute> to be more specific):
6ba6d68c 449
450=over 4
451
076c81ed 452=item I<is =E<gt> 'rw'|'ro'>
6ba6d68c 453
26fbace8 454The I<is> option accepts either I<rw> (for read/write) or I<ro> (for read
455only). These will create either a read/write accessor or a read-only
6ba6d68c 456accessor respectively, using the same name as the C<$name> of the attribute.
457
1b46b845 458If you need more control over how your accessors are named, you can
459use the L<reader|Class::MOP::Attribute/reader>,
460L<writer|Class::MOP::Attribute/writer> and
461L<accessor|Class::MOP::Attribute/accessor> options inherited from
462L<Class::MOP::Attribute>, however if you use those, you won't need the
463I<is> option.
6ba6d68c 464
076c81ed 465=item I<isa =E<gt> $type_name>
6ba6d68c 466
26fbace8 467The I<isa> option uses Moose's type constraint facilities to set up runtime
468type checking for this attribute. Moose will perform the checks during class
469construction, and within any accessors. The C<$type_name> argument must be a
470string. The string may be either a class name or a type defined using
9cca2e9e 471Moose's type definition features. (Refer to L<Moose::Util::TypeConstraints>
c2a69ef1 472for information on how to define a new type, and how to retrieve type meta-data).
6ba6d68c 473
daea75c9 474=item I<coerce =E<gt> (1|0)>
475
26fbace8 476This will attempt to use coercion with the supplied type constraint to change
2e953f12 477the value passed into any accessors or constructors. You B<must> supply a type
478constraint, and that type constraint B<must> defined a coercion. See
479L<Moose::Cookbook::Basics::Recipe5> for an example.
daea75c9 480
481=item I<does =E<gt> $role_name>
482
26fbace8 483This will accept the name of a role which the value stored in this attribute
daea75c9 484is expected to have consumed.
485
486=item I<required =E<gt> (1|0)>
487
81bec8f8 488This marks the attribute as being required. This means a value must be
be1355c0 489supplied during class construction, I<or> the attribute must be lazy
490and have either a default or a builder. Note that c<required> does not
491say anything about the attribute's value, which can be C<undef>.
daea75c9 492
493=item I<weak_ref =E<gt> (1|0)>
494
68efb014 495This will tell the class to store the value of this attribute as a weakened
496reference. If an attribute is a weakened reference, it B<cannot> also be
497coerced.
daea75c9 498
499=item I<lazy =E<gt> (1|0)>
500
26fbace8 501This will tell the class to not create this slot until absolutely necessary.
daea75c9 502If an attribute is marked as lazy it B<must> have a default supplied.
503
9e93dd19 504=item I<auto_deref =E<gt> (1|0)>
505
1668f3d7 506This tells the accessor to automatically dereference the value of this
507attribute when called in list context. The accessor will still return a
606cc2a6 508reference when called in scalar context. If this behavior isn't desirable,
509L<Moose::Meta::Attribute::Native::Trait::Array/elements> or
510L<Moose::Meta::Attribute::Native::Trait::Hash/elements> may be a better
511choice. The I<auto_deref> option is only legal if your I<isa> option is
512either C<ArrayRef> or C<HashRef>.
9e93dd19 513
65e14c86 514=item I<trigger =E<gt> $code>
515
525129a5 516The I<trigger> option is a CODE reference which will be called after
c25ca3a6 517the value of the attribute is set. The CODE ref is passed the
518instance itself, the updated value, and the original value if the
519attribute was already set.
3dda07f5 520
521You B<can> have a trigger on a read-only attribute.
010997ca 522
523B<NOTE:> Triggers will only fire when you B<assign> to the attribute,
524either in the constructor, or using the writer. Default and built values will
525B<not> cause the trigger to be fired.
daea75c9 526
c7761602 527=item I<handles =E<gt> ARRAY | HASH | REGEXP | ROLE | ROLETYPE | DUCKTYPE | CODE>
2c0cbef7 528
26fbace8 529The I<handles> option provides Moose classes with automated delegation features.
530This is a pretty complex and powerful option. It accepts many different option
531formats, each with its own benefits and drawbacks.
38e3283b 532
1cd45431 533B<NOTE:> The class being delegated to does not need to be a Moose based class,
534which is why this feature is especially useful when wrapping non-Moose classes.
38e3283b 535
1cd45431 536All I<handles> option formats share the following traits:
38e3283b 537
1cd45431 538You cannot override a locally defined method with a delegated method; an
539exception will be thrown if you try. That is to say, if you define C<foo> in
540your class, you cannot override it with a delegated C<foo>. This is almost never
541something you would want to do, and if it is, you should do it by hand and not
542use Moose.
38e3283b 543
1cd45431 544You cannot override any of the methods found in Moose::Object, or the C<BUILD>
545and C<DEMOLISH> methods. These will not throw an exception, but will silently
546move on to the next method in the list. My reasoning for this is that you would
547almost never want to do this, since it usually breaks your class. As with
548overriding locally defined methods, if you do want to do this, you should do it
549manually, not with Moose.
38e3283b 550
d03bd989 551You do not I<need> to have a reader (or accessor) for the attribute in order
552to delegate to it. Moose will create a means of accessing the value for you,
553however this will be several times B<less> efficient then if you had given
f3c4e20e 554the attribute a reader (or accessor) to use.
555
38e3283b 556Below is the documentation for each option format:
557
558=over 4
559
560=item C<ARRAY>
561
26fbace8 562This is the most common usage for I<handles>. You basically pass a list of
563method names to be delegated, and Moose will install a delegation method
1cd45431 564for each one.
38e3283b 565
566=item C<HASH>
567
26fbace8 568This is the second most common usage for I<handles>. Instead of a list of
569method names, you pass a HASH ref where each key is the method name you
570want installed locally, and its value is the name of the original method
571in the class being delegated to.
fd595040 572
26fbace8 573This can be very useful for recursive classes like trees. Here is a
5cfe3805 574quick example (soon to be expanded into a Moose::Cookbook recipe):
38e3283b 575
1cd45431 576 package Tree;
38e3283b 577 use Moose;
26fbace8 578
38e3283b 579 has 'node' => (is => 'rw', isa => 'Any');
26fbace8 580
38e3283b 581 has 'children' => (
582 is => 'ro',
583 isa => 'ArrayRef',
584 default => sub { [] }
585 );
26fbace8 586
38e3283b 587 has 'parent' => (
588 is => 'rw',
589 isa => 'Tree',
a4e516f6 590 weak_ref => 1,
38e3283b 591 handles => {
592 parent_node => 'node',
26fbace8 593 siblings => 'children',
38e3283b 594 }
595 );
596
1cd45431 597In this example, the Tree package gets C<parent_node> and C<siblings> methods,
598which delegate to the C<node> and C<children> methods (respectively) of the Tree
26fbace8 599instance stored in the C<parent> slot.
38e3283b 600
9218b114 601You may also use an array reference to curry arguments to the original method.
602
603 has 'thing' => (
604 ...
3c573ca4 605 handles => { set_foo => [ set => 'foo' ] },
9218b114 606 );
607
608 # $self->set_foo(...) calls $self->thing->set('foo', ...)
609
610The first element of the array reference is the original method name, and the
3c573ca4 611rest is a list of curried arguments.
9218b114 612
38e3283b 613=item C<REGEXP>
614
26fbace8 615The regexp option works very similar to the ARRAY option, except that it builds
616the list of methods for you. It starts by collecting all possible methods of the
617class being delegated to, then filters that list using the regexp supplied here.
38e3283b 618
26fbace8 619B<NOTE:> An I<isa> option is required when using the regexp option format. This
620is so that we can determine (at compile time) the method list from the class.
38e3283b 621Without an I<isa> this is just not possible.
622
c7761602 623=item C<ROLE> or C<ROLETYPE>
c84f324f 624
c7761602 625With the role option, you specify the name of a role or a
626L<role type|Moose::Meta::TypeConstraint::Role> whose "interface" then becomes
627the list of methods to handle. The "interface" can be defined as; the methods
628of the role and any required methods of the role. It should be noted that this
629does B<not> include any method modifiers or generated attribute methods (which
630is consistent with role composition).
c84f324f 631
e3de240e 632=item C<DUCKTYPE>
633
a6d8545f 634With the duck type option, you pass a duck type object whose "interface" then
635becomes the list of methods to handle. The "interface" can be defined as; the
636list of methods passed to C<duck_type> to create a duck type object. For more
637information on C<duck_type> please check
e9c2746e 638L<Moose::Util::TypeConstraints>.
e3de240e 639
38e3283b 640=item C<CODE>
641
1cd45431 642This is the option to use when you really want to do something funky. You should
643only use it if you really know what you are doing, as it involves manual
644metaclass twiddling.
38e3283b 645
1cd45431 646This takes a code reference, which should expect two arguments. The first is the
647attribute meta-object this I<handles> is attached to. The second is the
648metaclass of the class being delegated to. It expects you to return a hash (not
26fbace8 649a HASH ref) of the methods you want mapped.
38e3283b 650
651=back
2c0cbef7 652
004222dc 653=item I<metaclass =E<gt> $metaclass_name>
654
655This tells the class to use a custom attribute metaclass for this particular
656attribute. Custom attribute metaclasses are useful for extending the
657capabilities of the I<has> keyword: they are the simplest way to extend the MOP,
d03bd989 658but they are still a fairly advanced topic and too much to cover here, see
5cfe3805 659L<Moose::Cookbook::Meta::Recipe1> for more information.
004222dc 660
8a8856de 661See L<Metaclass and Trait Name Resolution> for details on how a metaclass name
662is resolved to a class name.
004222dc 663
664=item I<traits =E<gt> [ @role_names ]>
665
d03bd989 666This tells Moose to take the list of C<@role_names> and apply them to the
667attribute meta-object. This is very similar to the I<metaclass> option, but
54f2996d 668allows you to use more than one extension at a time.
004222dc 669
8a8856de 670See L<Metaclass and Trait Name Resolution> for details on how a trait name is
671resolved to a role name.
54f2996d 672
673Also see L<Moose::Cookbook::Meta::Recipe3> for a metaclass trait
674example.
004222dc 675
019f031d 676=item I<builder> => Str
010997ca 677
1b46b845 678The value of this key is the name of the method that will be called to
679obtain the value used to initialize the attribute. See the L<builder
680option docs in Class::MOP::Attribute|Class::MOP::Attribute/builder>
0bb2cc8a 681 and/or L<Moose::Cookbook::Basics::Recipe8> for more information.
010997ca 682
019f031d 683=item I<default> => SCALAR | CODE
010997ca 684
685The value of this key is the default value which will initialize the attribute.
686
1b46b845 687NOTE: If the value is a simple scalar (string or number), then it can
688be just passed as is. However, if you wish to initialize it with a
689HASH or ARRAY ref, then you need to wrap that inside a CODE reference.
690See the L<default option docs in
691Class::MOP::Attribute|Class::MOP::Attribute/default> for more
692information.
010997ca 693
019f031d 694=item I<clearer> => Str
010997ca 695
afd72e0c 696Creates a method allowing you to clear the value, see the L<clearer option
697docs in Class::MOP::Attribute|Class::MOP::Attribute/clearer> for more
1b46b845 698information.
010997ca 699
019f031d 700=item I<predicate> => Str
010997ca 701
afd72e0c 702Creates a method to perform a basic test to see if a value has been set in the
703attribute, see the L<predicate option docs in
704Class::MOP::Attribute|Class::MOP::Attribute/predicate> for more information.
010997ca 705
019f031d 706=item I<lazy_build> => (0|1)
707
708Automatically define lazy => 1 as well as builder => "_build_$attr", clearer =>
709"clear_$attr', predicate => 'has_$attr' unless they are already defined.
710
8c63a5c8 711=item I<initializer> => Str
712
713This may be a method name (referring to a method on the class with
714this attribute) or a CODE ref. The initializer is used to set the
715attribute value on an instance when the attribute is set during
716instance initialization (but not when the value is being assigned
717to). See the L<initializer option docs in
718Class::MOP::Attribute|Class::MOP::Attribute/initializer> for more
719information.
019f031d 720
60dcf673 721=item I<documentation> => $string
722
723An arbitrary string that can be retrieved later by calling C<<
724$attr->documentation >>.
725
726
727
6ba6d68c 728=back
729
cd7eeaf5 730=item B<has +$name =E<gt> %options>
731
c7874946 732This is variation on the normal attribute creator C<has> which allows you to
d03bd989 733clone and extend an attribute from a superclass or from a role. Here is an
8d62bf6d 734example of the superclass usage:
cd7eeaf5 735
736 package Foo;
737 use Moose;
26fbace8 738
cd7eeaf5 739 has 'message' => (
26fbace8 740 is => 'rw',
cd7eeaf5 741 isa => 'Str',
742 default => 'Hello, I am a Foo'
743 );
26fbace8 744
cd7eeaf5 745 package My::Foo;
746 use Moose;
26fbace8 747
cd7eeaf5 748 extends 'Foo';
26fbace8 749
cd7eeaf5 750 has '+message' => (default => 'Hello I am My::Foo');
751
1cd45431 752What is happening here is that B<My::Foo> is cloning the C<message> attribute
753from its parent class B<Foo>, retaining the C<is =E<gt> 'rw'> and C<isa =E<gt>
754'Str'> characteristics, but changing the value in C<default>.
cd7eeaf5 755
8d62bf6d 756Here is another example, but within the context of a role:
757
758 package Foo::Role;
759 use Moose::Role;
986d175a 760
8d62bf6d 761 has 'message' => (
762 is => 'rw',
763 isa => 'Str',
764 default => 'Hello, I am a Foo'
765 );
986d175a 766
8d62bf6d 767 package My::Foo;
768 use Moose;
986d175a 769
8d62bf6d 770 with 'Foo::Role';
986d175a 771
8d62bf6d 772 has '+message' => (default => 'Hello I am My::Foo');
773
d03bd989 774In this case, we are basically taking the attribute which the role supplied
775and altering it within the bounds of this feature.
8d62bf6d 776
73f70bdf 777Note that you can only extend an attribute from either a superclass or a role,
778you cannot extend an attribute in a role that composes over an attribute from
779another role.
780
d03bd989 781Aside from where the attributes come from (one from superclass, the other
782from a role), this feature works exactly the same. This feature is restricted
783somewhat, so as to try and force at least I<some> sanity into it. You are only
4032c9bb 784allowed to change the following attributes:
cd7eeaf5 785
786=over 4
787
26fbace8 788=item I<default>
cd7eeaf5 789
790Change the default value of an attribute.
791
26fbace8 792=item I<coerce>
cd7eeaf5 793
794Change whether the attribute attempts to coerce a value passed to it.
795
26fbace8 796=item I<required>
cd7eeaf5 797
798Change if the attribute is required to have a value.
799
800=item I<documentation>
801
802Change the documentation string associated with the attribute.
803
83cc9094 804=item I<lazy>
805
806Change if the attribute lazily initializes the slot.
807
cd7eeaf5 808=item I<isa>
809
d03bd989 810You I<are> allowed to change the type without restriction.
aed87761 811
d03bd989 812It is recommended that you use this freedom with caution. We used to
813only allow for extension only if the type was a subtype of the parent's
814type, but we felt that was too restrictive and is better left as a
815policy decision.
cd7eeaf5 816
83cc9094 817=item I<handles>
818
26fbace8 819You are allowed to B<add> a new C<handles> definition, but you are B<not>
820allowed to I<change> one.
83cc9094 821
8d62bf6d 822=item I<builder>
823
824You are allowed to B<add> a new C<builder> definition, but you are B<not>
825allowed to I<change> one.
826
13284479 827=item I<metaclass>
828
829You are allowed to B<add> a new C<metaclass> definition, but you are
830B<not> allowed to I<change> one.
831
832=item I<traits>
833
834You are allowed to B<add> additional traits to the C<traits> definition.
6549b0d1 835These traits will be composed into the attribute, but preexisting traits
13284479 836B<are not> overridden, or removed.
837
cd7eeaf5 838=back
839
78946cf8 840=item B<before $name|@names|\@names|qr/.../ =E<gt> sub { ... }>
6ba6d68c 841
78946cf8 842=item B<after $name|@names|\@names|qr/.../ =E<gt> sub { ... }>
6ba6d68c 843
78946cf8 844=item B<around $name|@names|\@names|qr/.../ =E<gt> sub { ... }>
6ba6d68c 845
e9f7d5c5 846These three items are syntactic sugar for the before, after, and around method
d8af92ae 847modifier features that L<Class::MOP> provides. More information on these may be
9b75e4b6 848found in L<Moose::Manual::MethodModifiers> and the
849L<Class::MOP::Class documentation|Class::MOP::Class/"Method Modifiers">.
6ba6d68c 850
159da176 851=item B<super>
852
26fbace8 853The keyword C<super> is a no-op when called outside of an C<override> method. In
854the context of an C<override> method, it will call the next most appropriate
159da176 855superclass method with the same arguments as the original method.
856
857=item B<override ($name, &sub)>
858
26fbace8 859An C<override> method is a way of explicitly saying "I am overriding this
860method from my superclass". You can call C<super> within this method, and
861it will work as expected. The same thing I<can> be accomplished with a normal
862method call and the C<SUPER::> pseudo-package; it is really your choice.
159da176 863
864=item B<inner>
865
26fbace8 866The keyword C<inner>, much like C<super>, is a no-op outside of the context of
867an C<augment> method. You can think of C<inner> as being the inverse of
68efb014 868C<super>; the details of how C<inner> and C<augment> work is best described in
5cfe3805 869the L<Moose::Cookbook::Basics::Recipe6>.
159da176 870
871=item B<augment ($name, &sub)>
872
26fbace8 873An C<augment> method, is a way of explicitly saying "I am augmenting this
874method from my superclass". Once again, the details of how C<inner> and
5cfe3805 875C<augment> work is best described in the L<Moose::Cookbook::Basics::Recipe6>.
159da176 876
6ba6d68c 877=item B<confess>
878
68efb014 879This is the C<Carp::confess> function, and exported here because I use it
d03bd989 880all the time.
6ba6d68c 881
882=item B<blessed>
883
1cd45431 884This is the C<Scalar::Util::blessed> function, it is exported here because I
26fbace8 885use it all the time. It is highly recommended that this is used instead of
6ba6d68c 886C<ref> anywhere you need to test for an object's class name.
887
888=back
889
c1381000 890=head1 METACLASS
54f2996d 891
c1381000 892When you use Moose, you can specify which metaclass to use:
893
894 use Moose -metaclass => 'My::Meta::Class';
895
896You can also specify traits which will be applied to your metaclass:
54f2996d 897
898 use Moose -traits => 'My::Trait';
899
900This is very similar to the attribute traits feature. When you do
901this, your class's C<meta> object will have the specified traits
8a8856de 902applied to it. See L<Metaclass and Trait Name Resolution> for more
903details.
54f2996d 904
8a8856de 905=head2 Metaclass and Trait Name Resolution
54f2996d 906
907By default, when given a trait name, Moose simply tries to load a
908class of the same name. If such a class does not exist, it then looks
909for for a class matching
910B<Moose::Meta::$type::Custom::Trait::$trait_name>. The C<$type>
911variable here will be one of B<Attribute> or B<Class>, depending on
912what the trait is being applied to.
913
914If a class with this long name exists, Moose checks to see if it has
915the method C<register_implementation>. This method is expected to
916return the I<real> class name of the trait. If there is no
917C<register_implementation> method, it will fall back to using
918B<Moose::Meta::$type::Custom::Trait::$trait> as the trait name.
919
8a8856de 920The lookup method for metaclasses is the same, except that it looks
921for a class matching B<Moose::Meta::$type::Custom::$metaclass_name>.
922
54f2996d 923If all this is confusing, take a look at
924L<Moose::Cookbook::Meta::Recipe3>, which demonstrates how to create an
925attribute trait.
926
1cd45431 927=head1 UNIMPORTING FUNCTIONS
31f8ec72 928
929=head2 B<unimport>
930
1cd45431 931Moose offers a way to remove the keywords it exports, through the C<unimport>
31f8ec72 932method. You simply have to say C<no Moose> at the bottom of your code for this
933to work. Here is an example:
934
935 package Person;
936 use Moose;
937
938 has 'first_name' => (is => 'rw', isa => 'Str');
939 has 'last_name' => (is => 'rw', isa => 'Str');
26fbace8 940
941 sub full_name {
31f8ec72 942 my $self = shift;
26fbace8 943 $self->first_name . ' ' . $self->last_name
31f8ec72 944 }
26fbace8 945
946 no Moose; # keywords are removed from the Person package
31f8ec72 947
9bcfbab1 948=head1 EXTENDING AND EMBEDDING MOOSE
949
5e86efbe 950To learn more about extending Moose, we recommend checking out the
951"Extending" recipes in the L<Moose::Cookbook>, starting with
952L<Moose::Cookbook::Extending::Recipe1>, which provides an overview of
953all the different ways you might extend Moose.
554b7648 954
955=head2 B<< Moose->init_meta(for_class => $class, base_class => $baseclass, metaclass => $metaclass) >>
9bcfbab1 956
554b7648 957The C<init_meta> method sets up the metaclass object for the class
b143539e 958specified by C<for_class>. This method injects a a C<meta> accessor
959into the class so you can get at this object. It also sets the class's
554b7648 960superclass to C<base_class>, with L<Moose::Object> as the default.
9bcfbab1 961
a8de959b 962C<init_meta> returns the metaclass object for C<$class>.
963
16fb3624 964You can specify an alternate metaclass with the C<metaclass> option.
26fbace8 965
80837fe1 966For more detail on this topic, see L<Moose::Cookbook::Extending::Recipe2>.
967
554b7648 968This method used to be documented as a function which accepted
969positional parameters. This calling style will still work for
4a66a4b3 970backwards compatibility, but is deprecated.
554b7648 971
972=head2 B<import>
973
974Moose's C<import> method supports the L<Sub::Exporter> form of C<{into =E<gt> $pkg}>
975and C<{into_level =E<gt> 1}>.
976
977B<NOTE>: Doing this is more or less deprecated. Use L<Moose::Exporter>
978instead, which lets you stack multiple C<Moose.pm>-alike modules
979sanely. It handles getting the exported functions into the right place
980for you.
981
23d3fe84 982=head2 B<throw_error>
4c0b3599 983
984An alias for C<confess>, used by internally by Moose.
985
a94f30ac 986=head2 The MooseX:: namespace
987
988Generally if you're writing an extension I<for> Moose itself you'll want
989to put your extension in the C<MooseX::> namespace. This namespace is
990specifically for extensions that make Moose better or different in some
991fundamental way. It is traditionally B<not> for a package that just happens
992to use Moose. This namespace follows from the examples of the C<LWPx::>
993and C<DBIx::> namespaces that perform the same function for C<LWP> and C<DBI>
994respectively.
995
6ea5491a 996=head1 METACLASS COMPATIBILITY AND MOOSE
997
998Metaclass compatibility is a thorny subject. You should start by
999reading the "About Metaclass compatibility" section in the
1000C<Class::MOP> docs.
1001
1002Moose will attempt to resolve a few cases of metaclass incompatibility
b9216044 1003when you set the superclasses for a class, in addition to the cases that
1004C<Class::MOP> handles.
1005
1006Moose tries to determine if the metaclasses only "differ by roles". This
1007means that the parent and child's metaclass share a common ancestor in
1008their respective hierarchies, and that the subclasses under the common
1009ancestor are only different because of role applications. This case is
1010actually fairly common when you mix and match various C<MooseX::*>
1011modules, many of which apply roles to the metaclass.
6ea5491a 1012
1013If the parent and child do differ by roles, Moose replaces the
1014metaclass in the child with a newly created metaclass. This metaclass
1015is a subclass of the parent's metaclass, does all of the roles that
1016the child's metaclass did before being replaced. Effectively, this
1017means the new metaclass does all of the roles done by both the
1018parent's and child's original metaclasses.
1019
1020Ultimately, this is all transparent to you except in the case of an
1021unresolvable conflict.
1022
05d9eaf6 1023=head1 CAVEATS
1024
1025=over 4
1026
1027=item *
1028
1cd45431 1029It should be noted that C<super> and C<inner> B<cannot> be used in the same
1030method. However, they may be combined within the same class hierarchy; see
1031F<t/014_override_augment_inner_super.t> for an example.
05d9eaf6 1032
26fbace8 1033The reason for this is that C<super> is only valid within a method
1034with the C<override> modifier, and C<inner> will never be valid within an
1035C<override> method. In fact, C<augment> will skip over any C<override> methods
68efb014 1036when searching for its appropriate C<inner>.
05d9eaf6 1037
1cd45431 1038This might seem like a restriction, but I am of the opinion that keeping these
1039two features separate (yet interoperable) actually makes them easy to use, since
1040their behavior is then easier to predict. Time will tell whether I am right or
c84f324f 1041not (UPDATE: so far so good).
05d9eaf6 1042
9b9da6f1 1043=back
1044
e49c11d2 1045=head1 GETTING HELP
1046
1047We offer both a mailing list and a very active IRC channel.
1048
1049The mailing list is L<moose@perl.org>. You must be subscribed to send
1050a message. To subscribe, send an empty message to
1051L<moose-subscribe@perl.org>
1052
236b8a02 1053You can also visit us at C<#moose> on L<irc://irc.perl.org/#moose>
60cbb35f 1054This channel is quite active, and questions at all levels (on Moose-related
1055topics ;) are welcome.
e49c11d2 1056
5569c072 1057=head1 ACKNOWLEDGEMENTS
1058
1059=over 4
1060
54c189df 1061=item I blame Sam Vilain for introducing me to the insanity that is meta-models.
5569c072 1062
54c189df 1063=item I blame Audrey Tang for then encouraging my meta-model habit in #perl6.
5569c072 1064
26fbace8 1065=item Without Yuval "nothingmuch" Kogman this module would not be possible,
54c189df 1066and it certainly wouldn't have this name ;P
5569c072 1067
26fbace8 1068=item The basis of the TypeContraints module was Rob Kinyon's idea
5569c072 1069originally, I just ran with it.
1070
638585e1 1071=item Thanks to mst & chansen and the whole #moose posse for all the
c84f324f 1072early ideas/feature-requests/encouragement/bug-finding.
d46a48f3 1073
68efb014 1074=item Thanks to David "Theory" Wheeler for meta-discussions and spelling fixes.
1075
5569c072 1076=back
1077
e90c03d0 1078=head1 SEE ALSO
1079
1080=over 4
1081
c84f324f 1082=item L<http://www.iinteractive.com/moose>
1083
6d137156 1084This is the official web home of Moose, it contains links to our public git repository
26fbace8 1085as well as links to a number of talks and articles on Moose and Moose related
1086technologies.
c84f324f 1087
196064ab 1088=item The Moose is flying, a tutorial by Randal Schwartz
1089
1090Part 1 - L<http://www.stonehenge.com/merlyn/LinuxMag/col94.html>
1091
1092Part 2 - L<http://www.stonehenge.com/merlyn/LinuxMag/col95.html>
1093
12aed9a0 1094=item Several Moose extension modules in the C<MooseX::> namespace.
1095
1096See L<http://search.cpan.org/search?query=MooseX::> for extensions.
28669f89 1097
e49c11d2 1098=item Moose stats on ohloh.net - L<http://www.ohloh.net/projects/moose>
1099
c84f324f 1100=back
1101
004222dc 1102=head2 Books
1103
1104=over 4
1105
1106=item The Art of the MetaObject Protocol
1107
d03bd989 1108I mention this in the L<Class::MOP> docs too, this book was critical in
004222dc 1109the development of both modules and is highly recommended.
1110
1111=back
1112
26fbace8 1113=head2 Papers
c84f324f 1114
1115=over 4
e90c03d0 1116
159da176 1117=item L<http://www.cs.utah.edu/plt/publications/oopsla04-gff.pdf>
1118
26fbace8 1119This paper (suggested by lbr on #moose) was what lead to the implementation
1120of the C<super>/C<override> and C<inner>/C<augment> features. If you really
1cd45431 1121want to understand them, I suggest you read this.
159da176 1122
e90c03d0 1123=back
1124
fcd84ca9 1125=head1 BUGS
1126
26fbace8 1127All complex software has bugs lurking in it, and this module is no
7efc4307 1128exception.
1129
1130Please report any bugs to C<bug-moose@rt.cpan.org>, or through the web
1131interface at L<http://rt.cpan.org>.
fcd84ca9 1132
0334ee02 1133You can also discuss feature requests or possible bugs on the Moose mailing
1134list (moose@perl.org) or on IRC at L<irc://irc.perl.org/#moose>.
1135
47b19570 1136=head1 FEATURE REQUESTS
1137
d03bd989 1138We are very strict about what features we add to the Moose core, especially
1139the user-visible features. Instead we have made sure that the underlying
1140meta-system of Moose is as extensible as possible so that you can add your
854b298d 1141own features easily.
1142
1143That said, occasionally there is a feature needed in the meta-system
1144to support your planned extension, in which case you should either
1145email the mailing list (moose@perl.org) or join us on IRC at
1146L<irc://irc.perl.org/#moose> to discuss. The
1147L<Moose::Manual::Contributing> has more detail about how and when you
1148can contribute.
47b19570 1149
fcd84ca9 1150=head1 AUTHOR
1151
d03bd989 1152Moose is an open project, there are at this point dozens of people who have
1153contributed, and can contribute. If you have added anything to the Moose
862ae2c4 1154project you have a commit bit on this file and can add your name to the list.
fcd84ca9 1155
862ae2c4 1156=head2 CABAL
1157
d03bd989 1158However there are only a few people with the rights to release a new version
862ae2c4 1159of Moose. The Moose Cabal are the people to go to with questions regarding
a4869d1e 1160the wider purview of Moose, and help out maintaining not just the code
958dc4e3 1161but the community as well.
862ae2c4 1162
1163Stevan (stevan) Little E<lt>stevan@iinteractive.comE<gt>
1164
2a267bff 1165Jesse (doy) Luehrs E<lt>doy at tozt dot netE<gt>
1166
862ae2c4 1167Yuval (nothingmuch) Kogman
1168
69ba075f 1169Shawn (sartak) Moore E<lt>sartak@bestpractical.comE<gt>
862ae2c4 1170
fd995afb 1171Hans Dieter (confound) Pearcey E<lt>hdp@pobox.comE<gt>
1172
d209e3ad 1173Chris (perigrin) Prather
1174
36edf31b 1175Florian Ragwitz E<lt>rafl@debian.orgE<gt>
d209e3ad 1176
2a267bff 1177Dave (autarch) Rolsky E<lt>autarch@urth.orgE<gt>
1178
862ae2c4 1179=head2 OTHER CONTRIBUTORS
db1ab48d 1180
9af1d28b 1181Aankhen
1182
1183Adam (Alias) Kennedy
1184
1185Anders (Debolaz) Nor Berle
1186
6549b0d1 1187Nathan (kolibrie) Gray
5868294f 1188
9af1d28b 1189Christian (chansen) Hansen
1190
1191Eric (ewilhelm) Wilhelm
1192
1193Guillermo (groditi) Roditi
1194
1195Jess (castaway) Robinson
1196
1197Matt (mst) Trout
1198
1199Robert (phaylon) Sedlacek
1200
1201Robert (rlb3) Boone
1202
1203Scott (konobi) McWhirter
1204
f44ae52f 1205Shlomi (rindolf) Fish
1206
68b6146c 1207Wallace (wreis) Reis
1208
e46f5cc2 1209Jonathan (jrockway) Rockway
1210
3ccdc84a 1211Piotr (dexter) Roszatycki
1212
26fbace8 1213Sam (mugwump) Vilain
f1917f58 1214
2f7e4042 1215Cory (gphat) Watson
1216
0be258b5 1217Dylan Hardison (doc fixes)
1218
9af1d28b 1219... and many other #moose folks
98aae381 1220
fcd84ca9 1221=head1 COPYRIGHT AND LICENSE
1222
7e0492d3 1223Copyright 2006-2010 by Infinity Interactive, Inc.
fcd84ca9 1224
1225L<http://www.iinteractive.com>
1226
1227This library is free software; you can redistribute it and/or modify
26fbace8 1228it under the same terms as Perl itself.
fcd84ca9 1229
ddd0ec20 1230=cut