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