95586cef3a60bad58679b35a6e16d275d42bbb86
[gitmo/Moose.git] / lib / Moose.pm
1
2 use FindBin;
3 use File::Spec;
4 use lib File::Spec->catdir(
5     $FindBin::Bin, 
6     File::Spec->updir,
7     File::Spec->updir,
8     File::Spec->updir,    
9     'Class-MOP',
10     'trunk',
11     'lib',
12 );
13
14 package Moose;
15
16 use strict;
17 use warnings;
18
19 our $VERSION = '0.18';
20
21 use Scalar::Util 'blessed', 'reftype';
22 use Carp         'confess';
23 use Sub::Name    'subname';
24 use B            'svref_2object';
25
26 use Sub::Exporter;
27
28 use Class::MOP;
29
30 use Moose::Meta::Class;
31 use Moose::Meta::TypeConstraint;
32 use Moose::Meta::TypeCoercion;
33 use Moose::Meta::Attribute;
34 use Moose::Meta::Instance;
35
36 use Moose::Object;
37 use Moose::Util::TypeConstraints;
38
39 {
40     my $CALLER;
41
42     sub _init_meta {
43         my $class = $CALLER;
44
45         # make a subtype for each Moose class
46         subtype $class
47             => as 'Object'
48             => where { $_->isa($class) }
49             => optimize_as { blessed($_[0]) && $_[0]->isa($class) }
50         unless find_type_constraint($class);
51
52         my $meta;
53         if ($class->can('meta')) {
54             # NOTE:
55             # this is the case where the metaclass pragma 
56             # was used before the 'use Moose' statement to 
57             # override a specific class
58             $meta = $class->meta();
59             (blessed($meta) && $meta->isa('Moose::Meta::Class'))
60                 || confess "You already have a &meta function, but it does not return a Moose::Meta::Class";
61         }
62         else {
63             # NOTE:
64             # this is broken currently, we actually need 
65             # to allow the possiblity of an inherited 
66             # meta, which will not be visible until the 
67             # user 'extends' first. This needs to have 
68             # more intelligence to it 
69             $meta = Moose::Meta::Class->initialize($class);
70             $meta->add_method('meta' => sub {
71                 # re-initialize so it inherits properly
72                 Moose::Meta::Class->initialize(blessed($_[0]) || $_[0]);
73             })
74         }
75
76         # make sure they inherit from Moose::Object
77         $meta->superclasses('Moose::Object')
78            unless $meta->superclasses();
79     }
80
81     my %exports = (
82         extends => sub {
83             my $class = $CALLER;
84             return subname 'Moose::extends' => sub (@) {
85                 confess "Must derive at least one class" unless @_;
86                 Class::MOP::load_class($_) for @_;
87                 # this checks the metaclass to make sure 
88                 # it is correct, sometimes it can get out 
89                 # of sync when the classes are being built
90                 my $meta = $class->meta->_fix_metaclass_incompatability(@_);
91                 $meta->superclasses(@_);
92             };
93         },
94         with => sub {
95             my $class = $CALLER;
96             return subname 'Moose::with' => sub (@) {
97                 my (@roles) = @_;
98                 confess "Must specify at least one role" unless @roles;
99                 Class::MOP::load_class($_) for @roles;
100                 $class->meta->_apply_all_roles(@roles);
101             };
102         },
103         has => sub {
104             my $class = $CALLER;
105             return subname 'Moose::has' => sub ($;%) {
106                 my ($name, %options) = @_;              
107                 $class->meta->_process_attribute($name, %options);
108             };
109         },
110         before => sub {
111             my $class = $CALLER;
112             return subname 'Moose::before' => sub (@&) {
113                 my $code = pop @_;
114                 my $meta = $class->meta;
115                 $meta->add_before_method_modifier($_, $code) for @_;
116             };
117         },
118         after => sub {
119             my $class = $CALLER;
120             return subname 'Moose::after' => sub (@&) {
121                 my $code = pop @_;
122                 my $meta = $class->meta;
123                 $meta->add_after_method_modifier($_, $code) for @_;
124             };
125         },
126         around => sub {
127             my $class = $CALLER;            
128             return subname 'Moose::around' => sub (@&) {
129                 my $code = pop @_;
130                 my $meta = $class->meta;
131                 $meta->add_around_method_modifier($_, $code) for @_;
132             };
133         },
134         super => sub {
135             return subname 'Moose::super' => sub {};
136         },
137         override => sub {
138             my $class = $CALLER;
139             return subname 'Moose::override' => sub ($&) {
140                 my ($name, $method) = @_;
141                 $class->meta->add_override_method_modifier($name => $method);
142             };
143         },
144         inner => sub {
145             return subname 'Moose::inner' => sub {};
146         },
147         augment => sub {
148             my $class = $CALLER;
149             return subname 'Moose::augment' => sub (@&) {
150                 my ($name, $method) = @_;
151                 $class->meta->add_augment_method_modifier($name => $method);
152             };
153         },
154         
155         # NOTE:
156         # this is experimental, but I am not 
157         # happy with it. If you want to try 
158         # it, you will have to uncomment it 
159         # yourself. 
160         # There is a really good chance that 
161         # this will be deprecated, dont get 
162         # too attached
163         # self => sub {
164         #     return subname 'Moose::self' => sub {};
165         # },        
166         # method => sub {
167         #     my $class = $CALLER;
168         #     return subname 'Moose::method' => sub {
169         #         my ($name, $method) = @_;
170         #         $class->meta->add_method($name, sub {
171         #             my $self = shift;
172         #             no strict   'refs';
173         #             no warnings 'redefine';
174         #             local *{$class->meta->name . '::self'} = sub { $self };
175         #             $method->(@_);
176         #         });
177         #     };
178         # },                
179         
180         confess => sub {
181             return \&Carp::confess;
182         },
183         blessed => sub {
184             return \&Scalar::Util::blessed;
185         },
186     );
187
188     my $exporter = Sub::Exporter::build_exporter({ 
189         exports => \%exports,
190         groups  => {
191             default => [':all']
192         }
193     });
194     
195     sub import {     
196         $CALLER = caller();
197         
198         strict->import;
199         warnings->import;        
200
201         # we should never export to main
202         return if $CALLER eq 'main';
203     
204         _init_meta();
205         
206         goto $exporter;
207     }
208     
209     sub unimport {
210         no strict 'refs';        
211         my $class = caller();
212         # loop through the exports ...
213         foreach my $name (keys %exports) {
214             next if $name =~ /inner|super|self/;
215             
216             # if we find one ...
217             if (defined &{$class . '::' . $name}) {
218                 my $keyword = \&{$class . '::' . $name};
219                 
220                 # make sure it is from Moose
221                 my $pkg_name = eval { svref_2object($keyword)->GV->STASH->NAME };
222                 next if $@;
223                 next if $pkg_name ne 'Moose';
224                 
225                 # and if it is from Moose then undef the slot
226                 delete ${$class . '::'}{$name};
227             }
228         }
229     }
230     
231     
232 }
233
234 ## make 'em all immutable
235
236 $_->meta->make_immutable(
237     inline_constructor => 0,
238     inline_accessors   => 0,    
239 ) for (
240     'Moose::Meta::Attribute',
241     'Moose::Meta::Class',
242     'Moose::Meta::Instance',
243
244     'Moose::Meta::TypeConstraint',
245     'Moose::Meta::TypeConstraint::Union',
246     'Moose::Meta::TypeCoercion',
247
248     'Moose::Meta::Method',
249     'Moose::Meta::Method::Accessor',
250     'Moose::Meta::Method::Constructor',
251     'Moose::Meta::Method::Overriden',
252 );
253
254 1;
255
256 __END__
257
258 =pod
259
260 =head1 NAME
261
262 Moose - A complete modern object system for Perl 5
263
264 =head1 SYNOPSIS
265
266   package Point;
267   use strict;
268   use warnings;
269   use Moose;
270         
271   has 'x' => (is => 'rw', isa => 'Int');
272   has 'y' => (is => 'rw', isa => 'Int');
273   
274   sub clear {
275       my $self = shift;
276       $self->x(0);
277       $self->y(0);    
278   }
279   
280   package Point3D;
281   use strict;
282   use warnings;  
283   use Moose;
284   
285   extends 'Point';
286   
287   has 'z' => (is => 'rw', isa => 'Int');
288   
289   after 'clear' => sub {
290       my $self = shift;
291       $self->z(0);
292   };
293   
294 =head1 CAVEAT
295
296 Moose is a rapidly maturing module, and is already being used by 
297 a number of people. It's test suite is growing larger by the day, 
298 and the docs should soon follow. 
299
300 This said, Moose is not yet finished, and should still be considered 
301 to be evolving. Much of the outer API is stable, but the internals 
302 are still subject to change (although not without serious thought 
303 given to it).  
304
305 =head1 DESCRIPTION
306
307 Moose is an extension of the Perl 5 object system. 
308
309 =head2 Another object system!?!?
310
311 Yes, I know there has been an explosion recently of new ways to 
312 build object's in Perl 5, most of them based on inside-out objects
313 and other such things. Moose is different because it is not a new 
314 object system for Perl 5, but instead an extension of the existing 
315 object system.
316
317 Moose is built on top of L<Class::MOP>, which is a metaclass system 
318 for Perl 5. This means that Moose not only makes building normal 
319 Perl 5 objects better, but it also provides the power of metaclass 
320 programming.
321
322 =head2 Can I use this in production? Or is this just an experiment?
323
324 Moose is I<based> on the prototypes and experiments I did for the Perl 6
325 meta-model; however Moose is B<NOT> an experiment/prototype, it is 
326 for B<real>. I will be deploying Moose into production environments later 
327 this year, and I have every intentions of using it as my de facto class 
328 builder from now on.
329
330 =head2 Is Moose just Perl 6 in Perl 5?
331
332 No. While Moose is very much inspired by Perl 6, it is not itself Perl 6.
333 Instead, it is an OO system for Perl 5. I built Moose because I was tired or
334 writing the same old boring Perl 5 OO code, and drooling over Perl 6 OO. So
335 instead of switching to Ruby, I wrote Moose :)
336
337 =head1 BUILDING CLASSES WITH MOOSE
338
339 Moose makes every attempt to provide as much convenience as possible during
340 class construction/definition, but still stay out of your way if you want it
341 to. Here are a few items to note when building classes with Moose.
342
343 Unless specified with C<extends>, any class which uses Moose will 
344 inherit from L<Moose::Object>.
345
346 Moose will also manage all attributes (including inherited ones) that 
347 are defined with C<has>. And assuming that you call C<new>, which is 
348 inherited from L<Moose::Object>, then this includes properly initializing 
349 all instance slots, setting defaults where appropriate, and performing any 
350 type constraint checking or coercion. 
351
352 =head1 EXPORTED FUNCTIONS
353
354 Moose will export a number of functions into the class's namespace which 
355 can then be used to set up the class. These functions all work directly 
356 on the current class.
357
358 =over 4
359
360 =item B<meta>
361
362 This is a method which provides access to the current class's metaclass.
363
364 =item B<extends (@superclasses)>
365
366 This function will set the superclass(es) for the current class.
367
368 This approach is recommended instead of C<use base>, because C<use base> 
369 actually C<push>es onto the class's C<@ISA>, whereas C<extends> will 
370 replace it. This is important to ensure that classes which do not have 
371 superclasses still properly inherit from L<Moose::Object>.
372
373 =item B<with (@roles)>
374
375 This will apply a given set of C<@roles> to the local class. Role support 
376 is currently under heavy development; see L<Moose::Role> for more details.
377
378 =item B<has ($name, %options)>
379
380 This will install an attribute of a given C<$name> into the current class. 
381 The list of C<%options> are the same as those provided by 
382 L<Class::MOP::Attribute>, in addition to the list below which are provided 
383 by Moose (L<Moose::Meta::Attribute> to be more specific):
384
385 =over 4
386
387 =item I<is =E<gt> 'rw'|'ro'>
388
389 The I<is> option accepts either I<rw> (for read/write) or I<ro> (for read 
390 only). These will create either a read/write accessor or a read-only 
391 accessor respectively, using the same name as the C<$name> of the attribute.
392
393 If you need more control over how your accessors are named, you can use the 
394 I<reader>, I<writer> and I<accessor> options inherited from L<Class::MOP::Attribute>.
395
396 =item I<isa =E<gt> $type_name>
397
398 The I<isa> option uses Moose's type constraint facilities to set up runtime 
399 type checking for this attribute. Moose will perform the checks during class 
400 construction, and within any accessors. The C<$type_name> argument must be a 
401 string. The string can be either a class name or a type defined using 
402 Moose's type definition features.
403
404 =item I<coerce =E<gt> (1|0)>
405
406 This will attempt to use coercion with the supplied type constraint to change 
407 the value passed into any accessors or constructors. You B<must> have supplied 
408 a type constraint in order for this to work. See L<Moose::Cookbook::Recipe5>
409 for an example usage.
410
411 =item I<does =E<gt> $role_name>
412
413 This will accept the name of a role which the value stored in this attribute 
414 is expected to have consumed.
415
416 =item I<required =E<gt> (1|0)>
417
418 This marks the attribute as being required. This means a value must be supplied 
419 during class construction, and the attribute can never be set to C<undef> with 
420 an accessor. 
421
422 =item I<weak_ref =E<gt> (1|0)>
423
424 This will tell the class to store the value of this attribute as a weakened
425 reference. If an attribute is a weakened reference, it B<cannot> also be
426 coerced.
427
428 =item I<lazy =E<gt> (1|0)>
429
430 This will tell the class to not create this slot until absolutely necessary. 
431 If an attribute is marked as lazy it B<must> have a default supplied.
432
433 =item I<auto_deref =E<gt> (1|0)>
434
435 This tells the accessor whether to automatically dereference the value returned. 
436 This is only legal if your C<isa> option is either an C<ArrayRef> or C<HashRef>.
437
438 =item I<trigger =E<gt> $code>
439
440 The trigger option is a CODE reference which will be called after the value of 
441 the attribute is set. The CODE ref will be passed the instance itself, the 
442 updated value and the attribute meta-object (this is for more advanced fiddling
443 and can typically be ignored in most cases). You B<cannot> have a trigger on
444 a read-only attribute.
445
446 =item I<handles =E<gt> [ @handles ]>
447
448 There is experimental support for attribute delegation using the C<handles> 
449 option. More docs to come later.
450
451 =back
452
453 =item B<before $name|@names =E<gt> sub { ... }>
454
455 =item B<after $name|@names =E<gt> sub { ... }>
456
457 =item B<around $name|@names =E<gt> sub { ... }>
458
459 This three items are syntactic sugar for the before, after, and around method 
460 modifier features that L<Class::MOP> provides. More information on these can 
461 be found in the L<Class::MOP> documentation for now. 
462
463 =item B<super>
464
465 The keyword C<super> is a no-op when called outside of an C<override> method. In  
466 the context of an C<override> method, it will call the next most appropriate 
467 superclass method with the same arguments as the original method.
468
469 =item B<override ($name, &sub)>
470
471 An C<override> method is a way of explicitly saying "I am overriding this 
472 method from my superclass". You can call C<super> within this method, and 
473 it will work as expected. The same thing I<can> be accomplished with a normal 
474 method call and the C<SUPER::> pseudo-package; it is really your choice. 
475
476 =item B<inner>
477
478 The keyword C<inner>, much like C<super>, is a no-op outside of the context of 
479 an C<augment> method. You can think of C<inner> as being the inverse of 
480 C<super>; the details of how C<inner> and C<augment> work is best described in
481 the L<Moose::Cookbook>.
482
483 =item B<augment ($name, &sub)>
484
485 An C<augment> method, is a way of explicitly saying "I am augmenting this 
486 method from my superclass". Once again, the details of how C<inner> and 
487 C<augment> work is best described in the L<Moose::Cookbook>.
488
489 =item B<confess>
490
491 This is the C<Carp::confess> function, and exported here because I use it
492 all the time. This feature may change in the future, so you have been warned. 
493
494 =item B<blessed>
495
496 This is the C<Scalar::Uti::blessed> function, it is exported here because I
497 use it all the time. It is highly recommended that this is used instead of 
498 C<ref> anywhere you need to test for an object's class name.
499
500 =back
501
502 =head1 UNEXPORTING FUNCTIONS
503
504 =head2 B<unimport>
505
506 Moose offers a way of removing the keywords it exports though the C<unimport>
507 method. You simply have to say C<no Moose> at the bottom of your code for this
508 to work. Here is an example:
509
510     package Person;
511     use Moose;
512
513     has 'first_name' => (is => 'rw', isa => 'Str');
514     has 'last_name'  => (is => 'rw', isa => 'Str');
515     
516     sub full_name { 
517         my $self = shift;
518         $self->first_name . ' ' . $self->last_name 
519     }
520     
521     no Moose; # keywords are removed from the Person package    
522
523 =head1 MISC.
524
525 =head2 What does Moose stand for??
526
527 Moose doesn't stand for one thing in particular, however, if you 
528 want, here are a few of my favorites; feel free to contribute
529 more :)
530
531 =over 4
532
533 =item Make Other Object Systems Envious
534
535 =item Makes Object Orientation So Easy
536
537 =item Makes Object Orientation Spiffy- Er  (sorry ingy)
538
539 =item Most Other Object Systems Emasculate
540
541 =item Moose Often Ovulate Sorta Early
542
543 =item Moose Offers Often Super Extensions
544
545 =item Meta Object Orientation Syntax Extensions
546
547 =back
548
549 =head1 CAVEATS
550
551 =over 4
552
553 =item *
554
555 It should be noted that C<super> and C<inner> C<cannot> be used in the same 
556 method. However, they can be combined together with the same class hierarchy;
557 see F<t/014_override_augment_inner_super.t> for an example. 
558
559 The reason for this is that C<super> is only valid within a method 
560 with the C<override> modifier, and C<inner> will never be valid within an 
561 C<override> method. In fact, C<augment> will skip over any C<override> methods 
562 when searching for its appropriate C<inner>.
563
564 This might seem like a restriction, but I am of the opinion that keeping these 
565 two features separate (but interoperable) actually makes them easy to use, since 
566 their behavior is then easier to predict. Time will tell if I am right or not.
567
568 =back
569
570 =head1 ACKNOWLEDGEMENTS
571
572 =over 4
573
574 =item I blame Sam Vilain for introducing me to the insanity that is meta-models.
575
576 =item I blame Audrey Tang for then encouraging my meta-model habit in #perl6.
577
578 =item Without Yuval "nothingmuch" Kogman this module would not be possible, 
579 and it certainly wouldn't have this name ;P
580
581 =item The basis of the TypeContraints module was Rob Kinyon's idea 
582 originally, I just ran with it.
583
584 =item Thanks to mst & chansen and the whole #moose poose for all the 
585 ideas/feature-requests/encouragement
586
587 =item Thanks to David "Theory" Wheeler for meta-discussions and spelling fixes.
588
589 =back
590
591 =head1 SEE ALSO
592
593 =over 4
594
595 =item L<Class::MOP> documentation
596
597 =item The #moose channel on irc.perl.org
598
599 =item The Moose mailing list - moose@perl.org
600
601 =item L<http://forum2.org/moose/>
602
603 =item L<http://www.cs.utah.edu/plt/publications/oopsla04-gff.pdf>
604
605 This paper (suggested by lbr on #moose) was what lead to the implementation 
606 of the C<super>/C<overrride> and C<inner>/C<augment> features. If you really 
607 want to understand this feature, I suggest you read this.
608
609 =back
610
611 =head1 BUGS
612
613 All complex software has bugs lurking in it, and this module is no 
614 exception. If you find a bug please either email me, or add the bug
615 to cpan-RT.
616
617 =head1 AUTHOR
618
619 Stevan Little E<lt>stevan@iinteractive.comE<gt>
620
621 Christian Hansen E<lt>chansen@cpan.orgE<gt>
622
623 Yuval Kogman E<lt>nothingmuch@woobling.orgE<gt>
624
625 =head1 COPYRIGHT AND LICENSE
626
627 Copyright 2006, 2007 by Infinity Interactive, Inc.
628
629 L<http://www.iinteractive.com>
630
631 This library is free software; you can redistribute it and/or modify
632 it under the same terms as Perl itself. 
633
634 =cut