subconstructor handling for Moose classes
[gitmo/Moo.git] / lib / Moo.pm
1 package Moo;
2
3 use strictures 1;
4 use Moo::_Utils;
5 use B 'perlstring';
6 use Sub::Defer ();
7
8 our $VERSION = '0.091009'; # 0.91.9
9 $VERSION = eval $VERSION;
10
11 require Moo::sification;
12
13 our %MAKERS;
14
15 sub import {
16   my $target = caller;
17   my $class = shift;
18   strictures->import;
19   return if $MAKERS{$target}; # already exported into this package
20   _install_coderef "${target}::extends" => "Moo::extends" => sub {
21     _load_module($_) for @_;
22     # Can't do *{...} = \@_ or 5.10.0's mro.pm stops seeing @ISA
23     @{*{_getglob("${target}::ISA")}{ARRAY}} = @_;
24     if (my $old = delete $Moo::MAKERS{$target}{constructor}) {
25       delete _getstash($target)->{new};
26       Moo->_constructor_maker_for($target)
27          ->register_attribute_specs(%{$old->all_attribute_specs});
28     }
29     $Moo::HandleMoose::MOUSE{$target} = [
30       grep defined, map Mouse::Util::find_meta($_), @_
31     ] if $INC{"Mouse.pm"};
32     $class->_maybe_reset_handlemoose($target);
33     return;
34   };
35   _install_coderef "${target}::with" => "Moo::with" => sub {
36     require Moo::Role;
37     Moo::Role->apply_roles_to_package($target, @_);
38     $class->_maybe_reset_handlemoose($target);
39   };
40   $MAKERS{$target} = {};
41   _install_coderef "${target}::has" => "Moo::has" => sub {
42     my ($name, %spec) = @_;
43     $class->_constructor_maker_for($target)
44           ->register_attribute_specs($name, \%spec);
45     $class->_accessor_maker_for($target)
46           ->generate_method($target, $name, \%spec);
47     $class->_maybe_reset_handlemoose($target);
48     return;
49   };
50   foreach my $type (qw(before after around)) {
51     _install_coderef "${target}::${type}" => "Moo::${type}" => sub {
52       require Class::Method::Modifiers;
53       _install_modifier($target, $type, @_);
54       return;
55     };
56   }
57   {
58     no strict 'refs';
59     @{"${target}::ISA"} = do {
60       require Moo::Object; ('Moo::Object');
61     } unless @{"${target}::ISA"};
62   }
63   if ($INC{'Moo/HandleMoose.pm'}) {
64     Moo::HandleMoose::inject_fake_metaclass_for($target);
65   }
66 }
67
68 sub _maybe_reset_handlemoose {
69   my ($class, $target) = @_;
70   if ($INC{"Moo/HandleMoose.pm"}) {
71     Moo::HandleMoose::maybe_reinject_fake_metaclass_for($target);
72   }
73 }
74
75 sub _accessor_maker_for {
76   my ($class, $target) = @_;
77   return unless $MAKERS{$target};
78   $MAKERS{$target}{accessor} ||= do {
79     my $maker_class = do {
80       if (my $m = do {
81             if (my $defer_target = 
82                   (Sub::Defer::defer_info($target->can('new'))||[])->[0]
83               ) {
84               my ($pkg) = ($defer_target =~ /^(.*)::[^:]+$/);
85               $MAKERS{$pkg} && $MAKERS{$pkg}{accessor};
86             } else {
87               undef;
88             }
89           }) {
90         ref($m);
91       } else {
92         require Method::Generate::Accessor;
93         'Method::Generate::Accessor'
94       }
95     };
96     $maker_class->new;
97   }
98 }
99
100 sub _constructor_maker_for {
101   my ($class, $target, $select_super) = @_;
102   return unless $MAKERS{$target};
103   $MAKERS{$target}{constructor} ||= do {
104     require Method::Generate::Constructor;
105     require Sub::Defer;
106     my ($moo_constructor, $con);
107
108     if ($select_super && $MAKERS{$select_super}) {
109       $moo_constructor = 1;
110       $con = $MAKERS{$select_super}{constructor};
111     } else {
112       my $t_new = $target->can('new');
113       if ($t_new) {
114         if ($t_new == Moo::Object->can('new')) {
115           $moo_constructor = 1;
116         } elsif (my $defer_target = (Sub::Defer::defer_info($t_new)||[])->[0]) {
117           my ($pkg) = ($defer_target =~ /^(.*)::[^:]+$/);
118           if ($MAKERS{$pkg}) {
119             $moo_constructor = 1;
120             $con = $MAKERS{$pkg}{constructor};
121           }
122         }
123       } else {
124         $moo_constructor = 1; # no other constructor, make a Moo one
125       }
126     };
127     ($con ? ref($con) : 'Method::Generate::Constructor')
128       ->new(
129         package => $target,
130         accessor_generator => $class->_accessor_maker_for($target),
131         construction_string => (
132           $moo_constructor
133             ? ($con ? $con->construction_string : undef)
134             : ('$class->'.$target.'::SUPER::new(@_)')
135         ),
136         subconstructor_handler => (
137           '      if ($Moo::MAKERS{$class}) {'."\n"
138           .'        '.$class.'->_constructor_maker_for($class,'.perlstring($target).');'."\n"
139           .'        return $class->new(@_)'.";\n"
140           .'      } elsif ($INC{"Moose.pm"} and my $meta = Class::MOP::get_metaclass_by_name($class)) {'."\n"
141           .'        return $meta->new_object(@_);'."\n"
142           .'      }'."\n"
143         ),
144       )
145       ->install_delayed
146       ->register_attribute_specs(%{$con?$con->all_attribute_specs:{}})
147   }
148 }
149
150 1;
151 =pod
152
153 =encoding utf-8
154
155 =head1 NAME
156
157 Moo - Minimalist Object Orientation (with Moose compatiblity)
158
159 =head1 SYNOPSIS
160
161  package Cat::Food;
162
163  use Moo;
164  use Sub::Quote;
165
166  sub feed_lion {
167    my $self = shift;
168    my $amount = shift || 1;
169
170    $self->pounds( $self->pounds - $amount );
171  }
172
173  has taste => (
174    is => 'ro',
175  );
176
177  has brand => (
178    is  => 'ro',
179    isa => sub {
180      die "Only SWEET-TREATZ supported!" unless $_[0] eq 'SWEET-TREATZ'
181    },
182 );
183
184  has pounds => (
185    is  => 'rw',
186    isa => quote_sub q{ die "$_[0] is too much cat food!" unless $_[0] < 15 },
187  );
188
189  1;
190
191 and else where
192
193  my $full = Cat::Food->new(
194     taste  => 'DELICIOUS.',
195     brand  => 'SWEET-TREATZ',
196     pounds => 10,
197  );
198
199  $full->feed_lion;
200
201  say $full->pounds;
202
203 =head1 DESCRIPTION
204
205 This module is an extremely light-weight, high-performance L<Moose> replacement.
206 It also avoids depending on any XS modules to allow simple deployments.  The
207 name C<Moo> is based on the idea that it provides almost -but not quite- two
208 thirds of L<Moose>.
209
210 Unlike C<Mouse> this module does not aim at full L<Moose> compatibility.  See
211 L</INCOMPATIBILITIES> for more details.
212
213 =head1 WHY MOO EXISTS
214
215 If you want a full object system with a rich Metaprotocol, L<Moose> is
216 already wonderful.
217
218 I've tried several times to use L<Mouse> but it's 3x the size of Moo and
219 takes longer to load than most of my Moo based CGI scripts take to run.
220
221 If you don't want L<Moose>, you don't want "less metaprotocol" like L<Mouse>,
222 you want "as little as possible" - which means "no metaprotocol", which is
223 what Moo provides.
224
225 By Moo 1.0 I intend to have Moo's equivalent of L<Any::Moose> built in -
226 if Moose gets loaded, any Moo class or role will act as a Moose equivalent
227 if treated as such.
228
229 Hence - Moo exists as its name - Minimal Object Orientation - with a pledge
230 to make it smooth to upgrade to L<Moose> when you need more than minimal
231 features.
232
233 =head1 Moo and Moose - NEW, EXPERIMENTAL
234
235 If L<Moo> detects L<Moose> being loaded, it will automatically register
236 metaclasses for your L<Moo> and L<Moo::Role> packages, so you should be able
237 to use them in L<Moose> code without it ever realising you aren't using
238 L<Moose> everywhere.
239
240 Extending a L<Moose> class or consuming a L<Moose::Role> should also work.
241
242 So should extending a L<Mouse> class or consuming a L<Mouse::Role>.
243
244 This means that there is no need for anything like L<Any::Moose> for Moo
245 code - Moo and Moose code should simply interoperate without problem. To
246 handle L<Mouse> code, you'll likely need an empty Moo role or class consuming
247 or extending the L<Mouse> stuff since it doesn't register true L<Moose>
248 metaclasses like we do.
249
250 However, these features are new as of 0.91.0 (0.091000) so while serviceable,
251 they are absolutely certain to not be 100% yet; please do report bugs.
252
253 If you need to disable the metaclass creation, add:
254
255   no Moo::sification;
256
257 to your code before Moose is loaded, but bear in mind that this switch is
258 currently global and turns the mechanism off entirely, so don't put this
259 in library code, only in a top level script as a temporary measure while
260 you send a bug report.
261
262 =head1 IMPORTED METHODS
263
264 =head2 new
265
266  Foo::Bar->new( attr1 => 3 );
267
268 or
269
270  Foo::Bar->new({ attr1 => 3 });
271
272 =head2 BUILDARGS
273
274  sub BUILDARGS {
275    my ( $class, @args ) = @_;
276
277    unshift @args, "attr1" if @args % 2 == 1;
278
279    return { @args };
280  };
281
282  Foo::Bar->new( 3 );
283
284 The default implementation of this method accepts a hash or hash reference of
285 named parameters. If it receives a single argument that isn't a hash reference
286 it throws an error.
287
288 You can override this method in your class to handle other types of options
289 passed to the constructor.
290
291 This method should always return a hash reference of named options.
292
293 =head2 BUILD
294
295 Define a C<BUILD> method on your class and the constructor will automatically
296 call the C<BUILD> method from parent down to child after the object has
297 been instantiated.  Typically this is used for object validation or possibly
298 logging.
299
300 =head2 DEMOLISH
301
302 If you have a C<DEMOLISH> method anywhere in your inheritance hierarchy,
303 a C<DESTROY> method is created on first object construction which will call
304 C<< $instance->DEMOLISH($in_global_destruction) >> for each C<DEMOLISH>
305 method from child upwards to parents.
306
307 Note that the C<DESTROY> method is created on first construction of an object
308 of your class in order to not add overhead to classes without C<DEMOLISH>
309 methods; this may prove slightly surprising if you try and define your own.
310
311 =head2 does
312
313  if ($foo->does('Some::Role1')) {
314    ...
315  }
316
317 Returns true if the object composes in the passed role.
318
319 =head1 IMPORTED SUBROUTINES
320
321 =head2 extends
322
323  extends 'Parent::Class';
324
325 Declares base class. Multiple superclasses can be passed for multiple
326 inheritance (but please use roles instead).
327
328 Calling extends more than once will REPLACE your superclasses, not add to
329 them like 'use base' would.
330
331 =head2 with
332
333  with 'Some::Role1';
334
335 or
336
337  with 'Some::Role1', 'Some::Role2';
338
339 Composes one or more L<Moo::Role> (or L<Role::Tiny>) roles into the current
340 class.  An error will be raised if these roles have conflicting methods.
341
342 =head2 has
343
344  has attr => (
345    is => 'ro',
346  );
347
348 Declares an attribute for the class.
349
350 The options for C<has> are as follows:
351
352 =over 2
353
354 =item * is
355
356 B<required>, may be C<ro>, C<lazy>, C<rwp> or C<rw>.
357
358 C<ro> generates an accessor that dies if you attempt to write to it - i.e.
359 a getter only - by defaulting C<reader> to the name of the attribute.
360
361 C<lazy> generates a reader like C<ro>, but also sets C<lazy> to 1 and
362 C<builder> to C<_build_${attribute_name}> to allow on-demand generated
363 attributes.  This feature was my attempt to fix my incompetence when
364 originally designing C<lazy_build>, and is also implemented by
365 L<MooseX::AttributeShortcuts>.
366
367 C<rwp> generates a reader like C<ro>, but also sets C<writer> to
368 C<_set_${attribute_name}> for attributes that are designed to be written
369 from inside of the class, but read-only from outside.
370 This feature comes from L<MooseX::AttributeShortcuts>.
371
372 C<rw> generates a normal getter/setter by defaulting C<accessor> to the
373 name of the attribute.
374
375 =item * isa
376
377 Takes a coderef which is meant to validate the attribute.  Unlike L<Moose> Moo
378 does not include a basic type system, so instead of doing C<< isa => 'Num' >>,
379 one should do
380
381  isa => quote_sub q{
382    die "$_[0] is not a number!" unless looks_like_number $_[0]
383  },
384
385 L<Sub::Quote aware|/SUB QUOTE AWARE>
386
387 Since L<Moo> does B<not> run the C<isa> check before C<coerce> if a coercion
388 subroutine has been supplied, C<isa> checks are not structural to your code
389 and can, if desired, be omitted on non-debug builds (although if this results
390 in an uncaught bug causing your program to break, the L<Moo> authors guarantee
391 nothing except that you get to keep both halves).
392
393 If you want L<MooseX::Types> style named types, look at
394 L<MooX::Types::MooseLike>.
395
396 To cause your C<isa> entries to be automatically mapped to named
397 L<Moose::Meta::TypeConstraint> objects (rather than the default behaviour
398 of creating an anonymous type), set:
399
400   $Moo::HandleMoose::TYPE_MAP{$isa_coderef} = sub {
401     require MooseX::Types::Something;
402     return MooseX::Types::Something::TypeName();
403   };
404
405 Note that this example is purely illustrative; anything that returns a
406 L<Moose::Meta::TypeConstraint> object or something similar enough to it to
407 make L<Moose> happy is fine.
408
409 =item * coerce
410
411 Takes a coderef which is meant to coerce the attribute.  The basic idea is to
412 do something like the following:
413
414  coerce => quote_sub q{
415    $_[0] + 1 unless $_[0] % 2
416  },
417
418 Note that L<Moo> will always fire your coercion - this is to permit
419 isa entries to be used purely for bug trapping, whereas coercions are
420 always structural to your code. We do, however, apply any supplied C<isa>
421 check after the coercion has run to ensure that it returned a valid value.
422
423 L<Sub::Quote aware|/SUB QUOTE AWARE>
424
425 =item * handles
426
427 Takes a string
428
429   handles => 'RobotRole'
430
431 Where C<RobotRole> is a role (L<Moo::Role>) that defines an interface which
432 becomes the list of methods to handle.
433
434 Takes a list of methods
435
436  handles => [ qw( one two ) ]
437
438 Takes a hashref
439
440  handles => {
441    un => 'one',
442  }
443
444 =item * trigger
445
446 Takes a coderef which will get called any time the attribute is set. This
447 includes the constructor. Coderef will be invoked against the object with the
448 new value as an argument.
449
450 If you set this to just C<1>, it generates a trigger which calls the
451 C<_trigger_${attr_name}> method on C<$self>. This feature comes from
452 L<MooseX::AttributeShortcuts>.
453
454 Note that Moose also passes the old value, if any; this feature is not yet
455 supported.
456
457 L<Sub::Quote aware|/SUB QUOTE AWARE>
458
459 =item * default
460
461 Takes a coderef which will get called with $self as its only argument
462 to populate an attribute if no value is supplied to the constructor - or
463 if the attribute is lazy, when the attribute is first retrieved if no
464 value has yet been provided.
465
466 Note that if your default is fired during new() there is no guarantee that
467 other attributes have been populated yet so you should not rely on their
468 existence.
469
470 L<Sub::Quote aware|/SUB QUOTE AWARE>
471
472 =item * predicate
473
474 Takes a method name which will return true if an attribute has a value.
475
476 If you set this to just C<1>, the predicate is automatically named
477 C<has_${attr_name}> if your attribute's name does not start with an
478 underscore, or <_has_${attr_name_without_the_underscore}> if it does.
479 This feature comes from L<MooseX::AttributeShortcuts>.
480
481 =item * builder
482
483 Takes a method name which will be called to create the attribute - functions
484 exactly like default except that instead of calling
485
486   $default->($self);
487
488 Moo will call
489
490   $self->$builder;
491
492 If you set this to just C<1>, the predicate is automatically named
493 C<_build_${attr_name}>.  This feature comes from L<MooseX::AttributeShortcuts>.
494
495 =item * clearer
496
497 Takes a method name which will clear the attribute.
498
499 If you set this to just C<1>, the clearer is automatically named
500 C<clear_${attr_name}> if your attribute's name does not start with an
501 underscore, or <_clear_${attr_name_without_the_underscore}> if it does.
502 This feature comes from L<MooseX::AttributeShortcuts>.
503
504 =item * lazy
505
506 B<Boolean>.  Set this if you want values for the attribute to be grabbed
507 lazily.  This is usually a good idea if you have a L</builder> which requires
508 another attribute to be set.
509
510 =item * required
511
512 B<Boolean>.  Set this if the attribute must be passed on instantiation.
513
514 =item * reader
515
516 The value of this attribute will be the name of the method to get the value of
517 the attribute.  If you like Java style methods, you might set this to
518 C<get_foo>
519
520 =item * writer
521
522 The value of this attribute will be the name of the method to set the value of
523 the attribute.  If you like Java style methods, you might set this to
524 C<set_foo>
525
526 =item * weak_ref
527
528 B<Boolean>.  Set this if you want the reference that the attribute contains to
529 be weakened; use this when circular references are possible, which will cause
530 leaks.
531
532 =item * init_arg
533
534 Takes the name of the key to look for at instantiation time of the object.  A
535 common use of this is to make an underscored attribute have a non-underscored
536 initialization name. C<undef> means that passing the value in on instantiation
537 is ignored.
538
539 =back
540
541 =head2 before
542
543  before foo => sub { ... };
544
545 See L<< Class::Method::Modifiers/before method(s) => sub { ... } >> for full
546 documentation.
547
548 =head2 around
549
550  around foo => sub { ... };
551
552 See L<< Class::Method::Modifiers/around method(s) => sub { ... } >> for full
553 documentation.
554
555 =head2 after
556
557  after foo => sub { ... };
558
559 See L<< Class::Method::Modifiers/after method(s) => sub { ... } >> for full
560 documentation.
561
562 =head1 SUB QUOTE AWARE
563
564 L<Sub::Quote/quote_sub> allows us to create coderefs that are "inlineable,"
565 giving us a handy, XS-free speed boost.  Any option that is L<Sub::Quote>
566 aware can take advantage of this.
567
568 =head1 INCOMPATIBILITIES WITH MOOSE
569
570 There is no built in type system.  C<isa> is verified with a coderef, if you
571 need complex types, just make a library of coderefs, or better yet, functions
572 that return quoted subs. L<MooX::Types::MooseLike> provides a similar API
573 to L<MooseX::Types::Moose> so that you can write
574
575   has days_to_live => (is => 'ro', isa => Int);
576
577 and have it work with both; it is hoped that providing only subrefs as an
578 API will encourage the use of other type systems as well, since it's
579 probably the weakest part of Moose design-wise.
580
581 C<initializer> is not supported in core since the author considers it to be a
582 bad idea but may be supported by an extension in future. Meanwhile C<trigger> or
583 C<coerce> are more likely to be able to fulfill your needs.
584
585 There is no meta object.  If you need this level of complexity you wanted
586 L<Moose> - Moo succeeds at being small because it explicitly does not
587 provide a metaprotocol. However, if you load L<Moose>, then
588
589   Class::MOP::class_of($moo_class_or_role)
590
591 will return an appropriate metaclass pre-populated by L<Moo>.
592
593 No support for C<super>, C<override>, C<inner>, or C<augment> - the author
594 considers augment to be a bad idea, and override can be translated:
595
596   override foo => sub {
597     ...
598     super();
599     ...
600   };
601
602   around foo => sub {
603     my ($orig, $self) = (shift, shift);
604     ...
605     $self->$orig(@_);
606     ...
607   };
608
609 The C<dump> method is not provided by default. The author suggests loading
610 L<Devel::Dwarn> into C<main::> (via C<perl -MDevel::Dwarn ...> for example) and
611 using C<$obj-E<gt>$::Dwarn()> instead.
612
613 L</default> only supports coderefs, because doing otherwise is usually a
614 mistake anyway.
615
616 C<lazy_build> is not supported; you are instead encouraged to use the
617 C<is => 'lazy'> option supported by L<Moo> and L<MooseX::AttributeShortcuts>.
618
619 C<auto_deref> is not supported since the author considers it a bad idea.
620
621 C<documentation> will show up in a L<Moose> metaclass created from your class
622 but is otherwise ignored. Then again, L<Moose> ignores it as well, so this
623 is arguably not an incompatibility.
624
625 Since C<coerce> does not require C<isa> to be defined but L<Moose> does
626 require it, the metaclass inflation for coerce-alone is a trifle insane
627 and if you attempt to subtype the result will almost certainly break.
628
629 Handling of warnings: when you C<use Moo> we enable FATAL warnings.  The nearest
630 similar invocation for L<Moose> would be:
631
632   use Moose;
633   use warnings FATAL => "all";
634
635 Additionally, L<Moo> supports a set of attribute option shortcuts intended to
636 reduce common boilerplate.  The set of shortcuts is the same as in the L<Moose>
637 module L<MooseX::AttributeShortcuts> as of its version 0.009+.  So if you:
638
639     package MyClass;
640     use Moo;
641
642 The nearest L<Moose> invocation would be:
643
644     package MyClass;
645
646     use Moose;
647     use warnings FATAL => "all";
648     use MooseX::AttributeShortcuts;
649
650 or, if you're inheriting from a non-Moose class,
651
652     package MyClass;
653
654     use Moose;
655     use MooseX::NonMoose;
656     use warnings FATAL => "all";
657     use MooseX::AttributeShortcuts;
658
659 Finally, Moose requires you to call
660
661     __PACKAGE__->meta->make_immutable;
662
663 at the end of your class to get an inlined (i.e. not horribly slow)
664 constructor. Moo does it automatically the first time ->new is called
665 on your class.
666
667 =head1 SUPPORT
668
669 IRC: #web-simple on irc.perl.org
670
671 =head1 AUTHOR
672
673 mst - Matt S. Trout (cpan:MSTROUT) <mst@shadowcat.co.uk>
674
675 =head1 CONTRIBUTORS
676
677 dg - David Leadbeater (cpan:DGL) <dgl@dgl.cx>
678
679 frew - Arthur Axel "fREW" Schmidt (cpan:FREW) <frioux@gmail.com>
680
681 hobbs - Andrew Rodland (cpan:ARODLAND) <arodland@cpan.org>
682
683 jnap - John Napiorkowski (cpan:JJNAPIORK) <jjn1056@yahoo.com>
684
685 ribasushi - Peter Rabbitson (cpan:RIBASUSHI) <ribasushi@cpan.org>
686
687 chip - Chip Salzenberg (cpan:CHIPS) <chip@pobox.com>
688
689 ajgb - Alex J. G. BurzyƄski (cpan:AJGB) <ajgb@cpan.org>
690
691 doy - Jesse Luehrs (cpan:DOY) <doy at tozt dot net>
692
693 perigrin - Chris Prather (cpan:PERIGRIN) <chris@prather.org>
694
695 =head1 COPYRIGHT
696
697 Copyright (c) 2010-2011 the Moo L</AUTHOR> and L</CONTRIBUTORS>
698 as listed above.
699
700 =head1 LICENSE
701
702 This library is free software and may be distributed under the same terms
703 as perl itself.
704
705 =cut