8 our $AUTHORITY = 'cpan:STEVAN';
10 use Scalar::Util 'blessed', 'reftype';
12 use Sub::Name 'subname';
18 use Moose::Meta::Class;
19 use Moose::Meta::TypeConstraint;
20 use Moose::Meta::TypeConstraint::Class;
21 use Moose::Meta::TypeCoercion;
22 use Moose::Meta::Attribute;
23 use Moose::Meta::Instance;
25 use Moose::Meta::Role;
28 use Moose::Util::TypeConstraints;
35 my ( $class, $base_class, $metaclass ) = @_;
36 $base_class = 'Moose::Object' unless defined $base_class;
37 $metaclass = 'Moose::Meta::Class' unless defined $metaclass;
40 "The Metaclass $metaclass must be a subclass of Moose::Meta::Class."
41 unless $metaclass->isa('Moose::Meta::Class');
43 # make a subtype for each Moose class
45 unless find_type_constraint($class);
48 if ( $class->can('meta') ) {
50 # this is the case where the metaclass pragma
51 # was used before the 'use Moose' statement to
52 # override a specific class
53 $meta = $class->meta();
54 ( blessed($meta) && $meta->isa('Moose::Meta::Class') )
55 || confess "You already have a &meta function, but it does not return a Moose::Meta::Class";
59 # this is broken currently, we actually need
60 # to allow the possiblity of an inherited
61 # meta, which will not be visible until the
62 # user 'extends' first. This needs to have
63 # more intelligence to it
64 $meta = $metaclass->initialize($class);
67 # re-initialize so it inherits properly
68 $metaclass->initialize( blessed( $_[0] ) || $_[0] );
73 # make sure they inherit from Moose::Object
74 $meta->superclasses($base_class)
75 unless $meta->superclasses();
83 return subname 'Moose::extends' => sub (@) {
84 confess "Must derive at least one class" unless @_;
87 foreach my $super (@supers) {
88 Class::MOP::load_class($super);
91 # this checks the metaclass to make sure
92 # it is correct, sometimes it can get out
93 # of sync when the classes are being built
94 my $meta = $class->meta->_fix_metaclass_incompatability(@supers);
95 $meta->superclasses(@supers);
100 return subname 'Moose::with' => sub (@) {
101 Moose::Util::apply_all_roles($class->meta, @_)
106 return subname 'Moose::has' => sub ($;%) {
108 die 'Usage: has \'name\' => ( key => value, ... )' if @_ == 1;
110 my $attrs = ( ref($name) eq 'ARRAY' ) ? $name : [ ($name) ];
111 $class->meta->add_attribute( $_, %options ) for @$attrs;
116 return subname 'Moose::before' => sub (@&) {
118 my $meta = $class->meta;
119 $meta->add_before_method_modifier( $_, $code ) for @_;
124 return subname 'Moose::after' => sub (@&) {
126 my $meta = $class->meta;
127 $meta->add_after_method_modifier( $_, $code ) for @_;
132 return subname 'Moose::around' => sub (@&) {
134 my $meta = $class->meta;
135 $meta->add_around_method_modifier( $_, $code ) for @_;
142 $SUPER_SLOT{$CALLER} = \*{"${CALLER}::super"};
144 return subname 'Moose::super' => sub { };
148 return subname 'Moose::override' => sub ($&) {
149 my ( $name, $method ) = @_;
150 $class->meta->add_override_method_modifier( $name => $method );
157 $INNER_SLOT{$CALLER} = \*{"${CALLER}::inner"};
159 return subname 'Moose::inner' => sub { };
163 return subname 'Moose::augment' => sub (@&) {
164 my ( $name, $method ) = @_;
165 $class->meta->add_augment_method_modifier( $name => $method );
170 return subname 'Moose::metaclass' => sub {
174 make_immutable => sub {
176 return subname 'Moose::make_immutable' => sub {
177 $class->meta->make_immutable(@_);
181 return \&Carp::confess;
184 return \&Scalar::Util::blessed;
188 my $exporter = Sub::Exporter::build_exporter(
190 exports => \%exports,
191 groups => { default => [':all'] }
195 # 1 extra level because it's called by import so there's a layer of indirection
199 ref $_[1] && defined $_[1]->{into}
201 : ref $_[1] && defined $_[1]->{into_level}
202 ? caller($offset + $_[1]->{into_level})
207 $CALLER = _get_caller(@_);
209 # this works because both pragmas set $^H (see perldoc perlvar)
210 # which affects the current compilation - i.e. the file who use'd
211 # us - which is why we don't need to do anything special to make
212 # it affect that file rather than this one (which is already compiled)
217 # we should never export to main
218 return if $CALLER eq 'main';
220 init_meta( $CALLER, 'Moose::Object' );
227 my $class = _get_caller(@_);
229 # loop through the exports ...
230 foreach my $name ( keys %exports ) {
233 if ( defined &{ $class . '::' . $name } ) {
234 my $keyword = \&{ $class . '::' . $name };
236 # make sure it is from Moose
237 my ($pkg_name) = Class::MOP::get_code_info($keyword);
239 next if $pkg_name ne 'Moose';
241 # and if it is from Moose then undef the slot
242 delete ${ $class . '::' }{$name};
249 ## make 'em all immutable
251 $_->meta->make_immutable(
252 inline_constructor => 0,
253 inline_accessors => 1, # these are Class::MOP accessors, so they need inlining
256 'Moose::Meta::Attribute',
257 'Moose::Meta::Class',
258 'Moose::Meta::Instance',
260 'Moose::Meta::TypeConstraint',
261 'Moose::Meta::TypeConstraint::Union',
262 'Moose::Meta::TypeConstraint::Parameterized',
263 'Moose::Meta::TypeCoercion',
265 'Moose::Meta::Method',
266 'Moose::Meta::Method::Accessor',
267 'Moose::Meta::Method::Constructor',
268 'Moose::Meta::Method::Destructor',
269 'Moose::Meta::Method::Overriden',
272 'Moose::Meta::Role::Method',
273 'Moose::Meta::Role::Method::Required',
284 Moose - A postmodern object system for Perl 5
289 use Moose; # automatically turns on strict and warnings
291 has 'x' => (is => 'rw', isa => 'Int');
292 has 'y' => (is => 'rw', isa => 'Int');
305 has 'z' => (is => 'rw', isa => 'Int');
307 after 'clear' => sub {
314 Moose is an extension of the Perl 5 object system.
316 =head2 Another object system!?!?
318 Yes, I know there has been an explosion recently of new ways to
319 build object's in Perl 5, most of them based on inside-out objects
320 and other such things. Moose is different because it is not a new
321 object system for Perl 5, but instead an extension of the existing
324 Moose is built on top of L<Class::MOP>, which is a metaclass system
325 for Perl 5. This means that Moose not only makes building normal
326 Perl 5 objects better, but it also provides the power of metaclass
329 =head2 Is this for real? Or is this just an experiment?
331 Moose is I<based> on the prototypes and experiments I did for the Perl 6
332 meta-model. However, Moose is B<NOT> an experiment/prototype; it is for B<real>.
334 =head2 Is this ready for use in production?
336 Yes, I believe that it is.
338 Moose has been used successfully in production environemnts by several people
339 and companies (including the one I work for). There are Moose applications
340 which have been in production with little or no issue now for well over a year.
341 I consider it highly stable and we are commited to keeping it stable.
343 Of course, in the end, you need to make this call yourself. If you have
344 any questions or concerns, please feel free to email me, or even the list
345 or just stop by #moose and ask away.
347 =head2 Is Moose just Perl 6 in Perl 5?
349 No. While Moose is very much inspired by Perl 6, it is not itself Perl 6.
350 Instead, it is an OO system for Perl 5. I built Moose because I was tired of
351 writing the same old boring Perl 5 OO code, and drooling over Perl 6 OO. So
352 instead of switching to Ruby, I wrote Moose :)
354 =head2 Wait, I<post> modern, I thought it was just I<modern>?
356 So I was reading Larry Wall's talk from the 1999 Linux World entitled
357 "Perl, the first postmodern computer language" in which he talks about how
358 he picked the features for Perl because he thought they were cool and he
359 threw out the ones that he thought sucked. This got me thinking about how
360 we have done the same thing in Moose. For Moose, we have "borrowed" features
361 from Perl 6, CLOS (LISP), Smalltalk, Java, BETA, OCaml, Ruby and more, and
362 the bits we didn't like (cause they sucked) we tossed aside. So for this
363 reason (and a few others) I have re-dubbed Moose a I<postmodern> object system.
367 =head2 Moose Extensions
369 The L<MooseX::> namespace is the official place to find Moose extensions.
370 There are a number of these modules out on CPAN right now the best way to
371 find them is to search for MooseX:: on search.cpan.org.
373 =head1 BUILDING CLASSES WITH MOOSE
375 Moose makes every attempt to provide as much convenience as possible during
376 class construction/definition, but still stay out of your way if you want it
377 to. Here are a few items to note when building classes with Moose.
379 Unless specified with C<extends>, any class which uses Moose will
380 inherit from L<Moose::Object>.
382 Moose will also manage all attributes (including inherited ones) that are
383 defined with C<has>. And (assuming you call C<new>, which is inherited from
384 L<Moose::Object>) this includes properly initializing all instance slots,
385 setting defaults where appropriate, and performing any type constraint checking
388 =head1 EXPORTED FUNCTIONS
390 Moose will export a number of functions into the class's namespace which
391 may then be used to set up the class. These functions all work directly
392 on the current class.
398 This is a method which provides access to the current class's metaclass.
400 =item B<extends (@superclasses)>
402 This function will set the superclass(es) for the current class.
404 This approach is recommended instead of C<use base>, because C<use base>
405 actually C<push>es onto the class's C<@ISA>, whereas C<extends> will
406 replace it. This is important to ensure that classes which do not have
407 superclasses still properly inherit from L<Moose::Object>.
409 =item B<with (@roles)>
411 This will apply a given set of C<@roles> to the local class. Role support
412 is currently under heavy development; see L<Moose::Role> for more details.
414 =item B<has $name =E<gt> %options>
416 This will install an attribute of a given C<$name> into the current class.
417 The C<%options> are the same as those provided by
418 L<Class::MOP::Attribute>, in addition to the list below which are provided
419 by Moose (L<Moose::Meta::Attribute> to be more specific):
423 =item I<is =E<gt> 'rw'|'ro'>
425 The I<is> option accepts either I<rw> (for read/write) or I<ro> (for read
426 only). These will create either a read/write accessor or a read-only
427 accessor respectively, using the same name as the C<$name> of the attribute.
429 If you need more control over how your accessors are named, you can use the
430 I<reader>, I<writer> and I<accessor> options inherited from
431 L<Class::MOP::Attribute>.
433 =item I<isa =E<gt> $type_name>
435 The I<isa> option uses Moose's type constraint facilities to set up runtime
436 type checking for this attribute. Moose will perform the checks during class
437 construction, and within any accessors. The C<$type_name> argument must be a
438 string. The string may be either a class name or a type defined using
439 Moose's type definition features. (Refer to L<Moose::Util::TypeConstraints>
440 for information on how to define a new type, and how to retrieve type meta-data).
442 =item I<coerce =E<gt> (1|0)>
444 This will attempt to use coercion with the supplied type constraint to change
445 the value passed into any accessors or constructors. You B<must> have supplied
446 a type constraint in order for this to work. See L<Moose::Cookbook::Recipe5>
449 =item I<does =E<gt> $role_name>
451 This will accept the name of a role which the value stored in this attribute
452 is expected to have consumed.
454 =item I<required =E<gt> (1|0)>
456 This marks the attribute as being required. This means a I<defined> value must be
457 supplied during class construction, and the attribute may never be set to
458 C<undef> with an accessor.
460 =item I<weak_ref =E<gt> (1|0)>
462 This will tell the class to store the value of this attribute as a weakened
463 reference. If an attribute is a weakened reference, it B<cannot> also be
466 =item I<lazy =E<gt> (1|0)>
468 This will tell the class to not create this slot until absolutely necessary.
469 If an attribute is marked as lazy it B<must> have a default supplied.
471 =item I<auto_deref =E<gt> (1|0)>
473 This tells the accessor whether to automatically dereference the value returned.
474 This is only legal if your C<isa> option is either C<ArrayRef> or C<HashRef>.
476 =item I<metaclass =E<gt> $metaclass_name>
478 This tells the class to use a custom attribute metaclass for this particular
479 attribute. Custom attribute metaclasses are useful for extending the
480 capabilities of the I<has> keyword: they are the simplest way to extend the MOP,
481 but they are still a fairly advanced topic and too much to cover here. I will
482 try and write a recipe on them soon.
484 The default behavior here is to just load C<$metaclass_name>; however, we also
485 have a way to alias to a shorter name. This will first look to see if
486 B<Moose::Meta::Attribute::Custom::$metaclass_name> exists. If it does, Moose
487 will then check to see if that has the method C<register_implementation>, which
488 should return the actual name of the custom attribute metaclass. If there is no
489 C<register_implementation> method, it will fall back to using
490 B<Moose::Meta::Attribute::Custom::$metaclass_name> as the metaclass name.
492 =item I<trigger =E<gt> $code>
494 The I<trigger> option is a CODE reference which will be called after the value of
495 the attribute is set. The CODE ref will be passed the instance itself, the
496 updated value and the attribute meta-object (this is for more advanced fiddling
497 and can typically be ignored). You B<cannot> have a trigger on a read-only
500 =item I<handles =E<gt> ARRAY | HASH | REGEXP | ROLE | CODE>
502 The I<handles> option provides Moose classes with automated delegation features.
503 This is a pretty complex and powerful option. It accepts many different option
504 formats, each with its own benefits and drawbacks.
506 B<NOTE:> This feature is no longer experimental, but it may still have subtle
507 bugs lurking in the deeper corners. If you think you have found a bug, you
508 probably have, so please report it to me right away.
510 B<NOTE:> The class being delegated to does not need to be a Moose based class,
511 which is why this feature is especially useful when wrapping non-Moose classes.
513 All I<handles> option formats share the following traits:
515 You cannot override a locally defined method with a delegated method; an
516 exception will be thrown if you try. That is to say, if you define C<foo> in
517 your class, you cannot override it with a delegated C<foo>. This is almost never
518 something you would want to do, and if it is, you should do it by hand and not
521 You cannot override any of the methods found in Moose::Object, or the C<BUILD>
522 and C<DEMOLISH> methods. These will not throw an exception, but will silently
523 move on to the next method in the list. My reasoning for this is that you would
524 almost never want to do this, since it usually breaks your class. As with
525 overriding locally defined methods, if you do want to do this, you should do it
526 manually, not with Moose.
528 You do not I<need> to have a reader (or accessor) for the attribute in order
529 to delegate to it. Moose will create a means of accessing the value for you,
530 however this will be several times B<less> efficient then if you had given
531 the attribute a reader (or accessor) to use.
533 Below is the documentation for each option format:
539 This is the most common usage for I<handles>. You basically pass a list of
540 method names to be delegated, and Moose will install a delegation method
545 This is the second most common usage for I<handles>. Instead of a list of
546 method names, you pass a HASH ref where each key is the method name you
547 want installed locally, and its value is the name of the original method
548 in the class being delegated to.
550 This can be very useful for recursive classes like trees. Here is a
551 quick example (soon to be expanded into a Moose::Cookbook::Recipe):
556 has 'node' => (is => 'rw', isa => 'Any');
561 default => sub { [] }
569 parent_node => 'node',
570 siblings => 'children',
574 In this example, the Tree package gets C<parent_node> and C<siblings> methods,
575 which delegate to the C<node> and C<children> methods (respectively) of the Tree
576 instance stored in the C<parent> slot.
580 The regexp option works very similar to the ARRAY option, except that it builds
581 the list of methods for you. It starts by collecting all possible methods of the
582 class being delegated to, then filters that list using the regexp supplied here.
584 B<NOTE:> An I<isa> option is required when using the regexp option format. This
585 is so that we can determine (at compile time) the method list from the class.
586 Without an I<isa> this is just not possible.
590 With the role option, you specify the name of a role whose "interface" then
591 becomes the list of methods to handle. The "interface" can be defined as; the
592 methods of the role and any required methods of the role. It should be noted
593 that this does B<not> include any method modifiers or generated attribute
594 methods (which is consistent with role composition).
598 This is the option to use when you really want to do something funky. You should
599 only use it if you really know what you are doing, as it involves manual
602 This takes a code reference, which should expect two arguments. The first is the
603 attribute meta-object this I<handles> is attached to. The second is the
604 metaclass of the class being delegated to. It expects you to return a hash (not
605 a HASH ref) of the methods you want mapped.
611 =item B<has +$name =E<gt> %options>
613 This is variation on the normal attibute creator C<has> which allows you to
614 clone and extend an attribute from a superclass or from a role. Here is an
615 example of the superclass usage:
623 default => 'Hello, I am a Foo'
631 has '+message' => (default => 'Hello I am My::Foo');
633 What is happening here is that B<My::Foo> is cloning the C<message> attribute
634 from its parent class B<Foo>, retaining the C<is =E<gt> 'rw'> and C<isa =E<gt>
635 'Str'> characteristics, but changing the value in C<default>.
637 Here is another example, but within the context of a role:
645 default => 'Hello, I am a Foo'
653 has '+message' => (default => 'Hello I am My::Foo');
655 In this case, we are basically taking the attribute which the role supplied
656 and altering it within the bounds of this feature.
658 Aside from where the attributes come from (one from superclass, the other
659 from a role), this feature works exactly the same. This feature is restricted
660 somewhat, so as to try and force at least I<some> sanity into it. You are only
661 allowed to change the following attributes:
667 Change the default value of an attribute.
671 Change whether the attribute attempts to coerce a value passed to it.
675 Change if the attribute is required to have a value.
677 =item I<documentation>
679 Change the documentation string associated with the attribute.
683 Change if the attribute lazily initializes the slot.
687 You I<are> allowed to change the type, B<if and only if> the new type is a
688 subtype of the old type.
692 You are allowed to B<add> a new C<handles> definition, but you are B<not>
693 allowed to I<change> one.
697 You are allowed to B<add> a new C<builder> definition, but you are B<not>
698 allowed to I<change> one.
702 =item B<before $name|@names =E<gt> sub { ... }>
704 =item B<after $name|@names =E<gt> sub { ... }>
706 =item B<around $name|@names =E<gt> sub { ... }>
708 This three items are syntactic sugar for the before, after, and around method
709 modifier features that L<Class::MOP> provides. More information on these may be
710 found in the L<Class::MOP::Class documentation|Class::MOP::Class/"Method
715 The keyword C<super> is a no-op when called outside of an C<override> method. In
716 the context of an C<override> method, it will call the next most appropriate
717 superclass method with the same arguments as the original method.
719 =item B<override ($name, &sub)>
721 An C<override> method is a way of explicitly saying "I am overriding this
722 method from my superclass". You can call C<super> within this method, and
723 it will work as expected. The same thing I<can> be accomplished with a normal
724 method call and the C<SUPER::> pseudo-package; it is really your choice.
728 The keyword C<inner>, much like C<super>, is a no-op outside of the context of
729 an C<augment> method. You can think of C<inner> as being the inverse of
730 C<super>; the details of how C<inner> and C<augment> work is best described in
731 the L<Moose::Cookbook>.
733 =item B<augment ($name, &sub)>
735 An C<augment> method, is a way of explicitly saying "I am augmenting this
736 method from my superclass". Once again, the details of how C<inner> and
737 C<augment> work is best described in the L<Moose::Cookbook>.
741 This is the C<Carp::confess> function, and exported here because I use it
742 all the time. This feature may change in the future, so you have been warned.
746 This is the C<Scalar::Util::blessed> function, it is exported here because I
747 use it all the time. It is highly recommended that this is used instead of
748 C<ref> anywhere you need to test for an object's class name.
752 =head1 UNIMPORTING FUNCTIONS
756 Moose offers a way to remove the keywords it exports, through the C<unimport>
757 method. You simply have to say C<no Moose> at the bottom of your code for this
758 to work. Here is an example:
763 has 'first_name' => (is => 'rw', isa => 'Str');
764 has 'last_name' => (is => 'rw', isa => 'Str');
768 $self->first_name . ' ' . $self->last_name
771 no Moose; # keywords are removed from the Person package
773 =head1 EXTENDING AND EMBEDDING MOOSE
775 Moose also offers some options for extending or embedding it into your own
776 framework. The basic premise is to have something that sets up your class'
777 metaclass and export the moose declarators (C<has>, C<with>, C<extends>,...).
784 my $CALLER = caller();
789 # we should never export to main
790 return if $CALLER eq 'main';
791 Moose::init_meta( $CALLER, 'MyFramework::Base' );
792 Moose->import({into => $CALLER});
794 # Do my custom framework stuff
801 Moose's C<import> method supports the L<Sub::Exporter> form of C<{into =E<gt> $pkg}>
802 and C<{into_level =E<gt> 1}>
804 =head2 B<init_meta ($class, $baseclass, $metaclass)>
806 Moose does some boot strapping: it creates a metaclass object for your class,
807 and then injects a C<meta> accessor into your class to retrieve it. Then it
808 sets your baseclass to Moose::Object or the value you pass in unless you already
809 have one. This is all done via C<init_meta> which takes the name of your class
810 and optionally a baseclass and a metaclass as arguments.
818 It should be noted that C<super> and C<inner> B<cannot> be used in the same
819 method. However, they may be combined within the same class hierarchy; see
820 F<t/014_override_augment_inner_super.t> for an example.
822 The reason for this is that C<super> is only valid within a method
823 with the C<override> modifier, and C<inner> will never be valid within an
824 C<override> method. In fact, C<augment> will skip over any C<override> methods
825 when searching for its appropriate C<inner>.
827 This might seem like a restriction, but I am of the opinion that keeping these
828 two features separate (yet interoperable) actually makes them easy to use, since
829 their behavior is then easier to predict. Time will tell whether I am right or
830 not (UPDATE: so far so good).
834 =head1 ACKNOWLEDGEMENTS
838 =item I blame Sam Vilain for introducing me to the insanity that is meta-models.
840 =item I blame Audrey Tang for then encouraging my meta-model habit in #perl6.
842 =item Without Yuval "nothingmuch" Kogman this module would not be possible,
843 and it certainly wouldn't have this name ;P
845 =item The basis of the TypeContraints module was Rob Kinyon's idea
846 originally, I just ran with it.
848 =item Thanks to mst & chansen and the whole #moose poose for all the
849 early ideas/feature-requests/encouragement/bug-finding.
851 =item Thanks to David "Theory" Wheeler for meta-discussions and spelling fixes.
859 =item L<http://www.iinteractive.com/moose>
861 This is the official web home of Moose, it contains links to our public SVN repo
862 as well as links to a number of talks and articles on Moose and Moose related
865 =item L<Class::MOP> documentation
867 =item The #moose channel on irc.perl.org
869 =item The Moose mailing list - moose@perl.org
871 =item Moose stats on ohloh.net - L<http://www.ohloh.net/projects/5788>
873 =item Several Moose extension modules in the L<MooseX::> namespace.
881 =item L<http://www.cs.utah.edu/plt/publications/oopsla04-gff.pdf>
883 This paper (suggested by lbr on #moose) was what lead to the implementation
884 of the C<super>/C<override> and C<inner>/C<augment> features. If you really
885 want to understand them, I suggest you read this.
891 All complex software has bugs lurking in it, and this module is no
892 exception. If you find a bug please either email me, or add the bug
897 Stevan Little E<lt>stevan@iinteractive.comE<gt>
899 B<with contributions from:>
905 Anders (Debolaz) Nor Berle
907 Nathan (kolibre) Gray
909 Christian (chansen) Hansen
911 Hans Dieter (confound) Pearcey
913 Eric (ewilhelm) Wilhelm
915 Guillermo (groditi) Roditi
917 Jess (castaway) Robinson
921 Robert (phaylon) Sedlacek
925 Scott (konobi) McWhirter
927 Shlomi (rindolf) Fish
929 Yuval (nothingmuch) Kogman
931 Chris (perigrin) Prather
933 Jonathan (jrockway) Rockway
935 Piotr (dexter) Roszatycki
941 ... and many other #moose folks
943 =head1 COPYRIGHT AND LICENSE
945 Copyright 2006-2008 by Infinity Interactive, Inc.
947 L<http://www.iinteractive.com>
949 This library is free software; you can redistribute it and/or modify
950 it under the same terms as Perl itself.