I was channeling stevan and misspeled declaratively
[gitmo/Moose.git] / lib / Moose / Intro.pod
CommitLineData
270df362 1=pod
2
3=head1 NAME
4
5Moose::Intro - What is Moose, and how do I use it?
6
7=head1 WHAT IS MOOSE?
8
9Moose is a I<complete> object system for Perl 5. If you've used a
10821858 10modern object-oriented language (which Perl 5 definitely isn't), you
11know they provide keywords for attribute declaration, object
12construction, and inheritance. These keywords are part of the
13language, and you don't care how they are implemented.
270df362 14
15Moose aims to do the same thing for Perl 5 OO. We can't actually
10821858 16create new keywords, but we do offer "sugar" that looks a lot like
9f0ce58b 17them. More importantly, with Moose, you I<declaratively define> your
10821858 18class, without needing to know about blessed hashrefs, accessor
19methods, and so on.
270df362 20
10821858 21Moose lets you focus on the I<logical> structure of your classes, so
22you can focus on "what" rather than "how". With Moose, a class
23definition should read like a list of very concise English sentences.
270df362 24
25Moose is built in top of C<Class::MOP>, a meta-object protocol (aka
26MOP). Using the MOP, Moose provides complete introspection for all
27Moose-using classes. This means you can ask classes about their
28attributes, parents, children, methods, etc., all using a well-defined
10821858 29API. The MOP abstracts away tedious digging about in the Perl symbol
30table, looking at C<@ISA> vars, and all the other crufty Perl tricks
31we know and love (?).
270df362 32
10821858 33Moose is based in large part on the Perl 6 object system, as well as
34drawing on the best ideas from CLOS, Smalltalk, and many other
35languages.
270df362 36
37=head1 WHY MOOSE?
38
10821858 39Moose makes Perl 5 OO both simpler and more powerful. It encapsulates
40all the tricks of Perl 5 power users in high-level declarative APIs
41which are easy to use, and don't require any special knowledge of how
42Perl works under the hood.
270df362 43
44Moose makes Perl 5 OO fun, accessible, and powerful. And if you want
10821858 45to dig about in the guts, Moose lets you do that too, by using and
46extending its powerful introspection API.
270df362 47
48=head1 AN EXAMPLE
49
50 package Person;
51
52 use Moose;
53
54 has 'first_name' => (
55 is => 'rw',
56 isa => 'Str',
57 );
58
59 has 'last_name' => (
60 is => 'rw',
61 isa => 'Str',
62 );
63
64This is a I<complete and usable> class definition!
65
66 package User;
67
68 use DateTime;
69 use Moose;
70
71 extends 'Person';
72
73 has 'password' => (
74 is => 'rw',
f330de33 75 isa => 'Str',
76 );
270df362 77
78 has 'last_login' => (
79 is => 'rw',
80 isa => 'DateTime',
fec9ca3e 81 handles => { 'date_of_last_login' => 'date' },
270df362 82 );
83
84 sub login {
85 my $self = shift;
86 my $pw = shift;
87
88 return 0 if $pw ne $self->password;
89
90 $self->last_login( DateTime->now() );
91
92 return 1;
93 }
94
95We'll leave the line-by-line explanation of this code to other
10821858 96documentation, but you can see how Moose reduces common OO idioms to
97simple declarative constructs.
270df362 98
99=head2 Where's the Constructor?
100
101One point of confusion that might come up with Moose is how it handles
102object construction. B<You should not define a C<new()> method for
103your classes!>
104
105Moose will provide one for you. It will accept a hash or hash
106reference of named parameters matching your attributes. This is just
cb4abcc5 107another way in which Moose keeps you from worrying I<how> classes are
270df362 108implemented. Simply define a class and you're ready to start creating
109objects!
110
10821858 111=head1 MOOSE CONCEPTS (VS "OLD SCHOOL" Perl)
270df362 112
10821858 113In the past, you may not have thought too much about the difference
cb4abcc5 114between packages and classes, attributes and methods, constructors and
10821858 115methods, etc. Part of what the MOP provides is well-defined
116introspection features for each of those things, and in turn Moose
117provides I<distinct> sugar for each of them. Moose also introduces
118concepts that are uncommon (or entirely new) like roles, method
119modifiers, and declarative delegation.
270df362 120
10821858 121Knowing what these concepts mean in Moose-speak, and how they used to
122be done in old school Perl 5 OO is a good way to start learning to use
123Moose.
270df362 124
125=head2 Class
126
127When you say "use Moose" in a package, you are defining your package
10821858 128as a class. At its simplest, a class will consist simply of attributes
270df362 129and/or methods. It can also include roles, method modifiers, and more.
130
10821858 131A class I<has> zero or more B<attributes>.
270df362 132
133A class I<has> zero or more B<methods>.
134
3f67b9e0 135A class I<has> zero or more superclasses (aka parent classes). A
270df362 136class inherits from its superclass(es).
137
3f67b9e0 138A class I<has> zero or more B<method modifiers>. These modifiers can
139apply to its own methods or methods that are inherited from its
140ancestors.
270df362 141
142A class may I<do> one or more B<roles>.
143
10821858 144A class I<has> a B<constructor> and a B<destructor>. These are
145provided for you "for free" by Moose.
146
147The B<constructor> accepts named parameters corresponding to the
cb4abcc5 148class's attributes and uses them to initialize an B<object instance>.
270df362 149
150A class I<has> a B<metaclass>, which in turn has B<meta-attributes>,
151B<meta-methods>, and B<meta-roles>. This metaclass I<describes> the
152class.
153
154A class is usually analogous to a category of nouns, like "People" or
155"Users".
156
10821858 157 package Person;
158
159 use Moose;
160 # now it's a Moose class!
161
270df362 162=head2 Attribute
163
164An attribute is a property of the class that defines it. It I<always>
10821858 165has a name, and it I<may have> a number of other defining
166characteristics.
270df362 167
10821858 168These characteristics may include a read/write flag, a B<type>,
169accessor method names, B<delegations>, a default value, and more.
270df362 170
10821858 171Attributes I<are not> methods, but defining them causes various
172accessor methods to be created. At a minimum, a normal attribute will
173always have a reader accessor method. Many attributes have things like
174a writer method, clearer method, and predicate method ("has it been
175set?").
176
177An attribute may also define B<delegation>s, which will create
178additional methods based on the delegation specification.
270df362 179
180By default, Moose stores attributes in the object instance, which is a
10821858 181hashref, I<but this is invisible to the author of a Moose-base class>!
182It is best to think of Moose attributes as "properties" of the
183I<opaque> B<object instance>. These properties are accessed through
184well-defined accessor methods.
270df362 185
c2f24a52 186An attribute is usually analogous to a specific feature of something in
270df362 187the class's category. For example, People have first and last
188names. Users have passwords and last login datetimes.
189
10821858 190 has 'first_name' => (
191 is => 'rw',
192 isa => 'Str',
193 );
194
270df362 195=head2 Method
196
197A method is very straightforward. Any subroutine you define in your
198class is a method.
199
200Methods correspond to verbs, and are what your objects can do. For
201example, a User can login.
202
10821858 203 sub login { ... }
204
270df362 205=head2 Roles
206
207A role is something that a class I<does>. For example, a Machine class
cb4abcc5 208might do the Breakable role, and so could a Bone class. A role is
270df362 209used to define some concept that cuts across multiple unrelated
10821858 210classes, like "breakability", or "has a color".
270df362 211
212A role I<has> zero or more B<attributes>.
213
214A role I<has> zero or more B<methods>.
215
216A role I<has> zero or more B<method modifiers>.
217
218A role I<has> zero or more B<required methods>.
219
220A required method is not implemented by the role. Instead, a required
221method says "to use this Role you must implement this method".
222
223Roles are I<composed> into classes (or other roles). When a role is
224composed into a class, its attributes and methods are "flattened" into
225the class. Roles I<do not> show up in the inheritance hierarchy. When
cb4abcc5 226a role is composed, its attributes and methods appear as if they were
270df362 227defined I<in the consuming class>.
228
229Role are somewhat like mixins or interfaces in other OO languages.
230
231 package Breakable;
232
233 use Moose::Role;
234
235 has is_broken => (
236 is => 'rw',
237 isa => 'Bool',
238 );
239
240 requires 'break';
241
242 before 'break' => {
243 my $self = shift;
244
245 $self->is_broken(1);
246 };
247
248=head2 Method Modifiers
249
250A method modifier is a way of defining an action to be taken when a
10821858 251named method is called. Think of it as a hook on the named method. For
252example, you could say "before calling C<login()>, call this modifier
253first". Modifiers come in different flavors like "before", "after",
254"around", and "augment", and you can apply more than one modifier to
255a single method.
270df362 256
257Method modifiers are often used as an alternative to overriding a
258method in a parent class. They are also used in roles as a way of
259modifying methods in the consuming class.
260
261Under the hood, a method modifier is just a plain old Perl subroutine
10821858 262that gets called before or after (or around, etc.) some named method.
270df362 263
264 before 'login' => sub {
265 my $self = shift;
266 my $pw = shift;
267
268 warn "Called login() with $pw\n";
269 };
270
271=head2 Type
272
273Moose also comes with a (miniature) type system. This allows you to
274define types for attributes. Moose has a set of built-in types based
275on what Perl provides, such as "Str", "Num", "Bool", "HashRef", etc.
276
277In addition, every class name in your application can also be used as
278a type name. We saw an example using "DateTime" earlier.
279
280Finally, you can define your own types, either as subtypes or entirely
281new types, with their own constraints. For example, you could define a
10821858 282type "PosInt", a subtype of "Int" which only allows positive numbers.
270df362 283
284=head2 Delegation
285
286Moose attributes provide declarative syntax for defining
287delegations. A delegation is a method which delegates the real work to
288some attribute of the class.
289
10821858 290You saw this in the User example, where we defined a delegation for
fec9ca3e 291the C<date_of_last_login()> method. Under the hood, this simple calls
f1344ac1 292C<date()> on the User object's C<last_login> attribute.
270df362 293
294=head2 Constructor
295
296A constructor creates an B<object instance> for the class. In old
297school Perl, this was usually done by defining a method called
298C<new()> which in turn called C<bless> on a reference.
299
300With Moose, this C<new()> method is created for you, and it simply
301does the right thing. You should never need to define your own
10821858 302constructor!
270df362 303
bc8641fc 304Sometimes you want to do something whenever an object is created. In
305those cases, you can provide a C<BUILD()> method in your class. Moose
306will call this for you after creating a new object.
307
270df362 308=head2 Destructor
309
310This is a special method called when an object instance goes out of
311scope. You can specialize what your class does in this method if you
312need to, but you usually don't.
313
314With old school Perl 5, this is the C<DESTROY()> method, but with
315Moose it is the C<DEMOLISH()> method.
316
317=head2 Object Instance
318
319An object instance is a specific noun in the class's "category". For
320example, one specific Person or User. An instance is created by the
321class's B<constructor>.
322
323An instance has values for its attributes. For example, a specific
cb4abcc5 324person has a first and last name.
270df362 325
326In old school Perl 5, this is often a blessed hash reference. With
327Moose, you should never need to know what your object instance
328actually is. (ok, it's usually a blessed hashref with Moose too)
329
330=head2 Moose VS Old School Summary
331
332=over 4
333
10821858 334=item * Class
270df362 335
336A package with no introspection other than mucking about in the symbol
337table.
338
339With Moose, you get well-defined declaration and introspection.
340
10821858 341=item * Attributes
270df362 342
343Hand-written accessor methods, symbol table hackery, or a helper
344module like C<Class::Accessor>.
345
9f0ce58b 346With Moose, these are declaratively defined, and distinct from
270df362 347methods.
348
10821858 349=item * Method
270df362 350
10821858 351These are pretty much the same in Moose as in old school Perl.
270df362 352
353=item * Roles
354
355C<Class::Trait> or C<Class::Role>, or maybe C<mixin.pm>.
356
357With Moose, they're part of the core feature set, and are
358introspectable like everything else.
359
360=item * Method Modifiers
361
362Could only be done through serious symbol table wizardry, and you
363probably never saw this before (at least in Perl 5).
364
365=item * Type
366
367Hand-written parameter checking in your C<new()> method and accessors.
368
369With Moose, you define types declaratively, and then use them by name
370in your attributes.
371
372=item * Delegation
373
374C<Class::Delegation> or C<Class::Delegator>, but probably even more
375hand-written code.
376
377With Moose, this is also declarative.
378
379=item * Constructor
380
381A C<new()> method which calls C<bless> on a reference.
382
10821858 383Comes for free when you define a class with Moose.
270df362 384
385=item * Destructor
386
387A C<DESTROY()> method.
388
389With Moose, this is called C<DEMOLISH()>.
390
391=item * Object Instance
392
393A blessed reference, usually a hash reference.
394
395With Moose, this is an opaque thing which has a bunch of attributes
396and methods, as defined by its class.
397
e03c5ed2 398=item * Immutabilization
399
400Moose comes with a feature called "immutabilization". When you make
401your class immutable, it means you're done adding methods, attributes,
402roles, etc. This lets Moose optimize your class with a bunch of
403extremely dirty in-place code generation tricks that speed up things
404like object construction and so on.
405
270df362 406=back
407
408=head1 META WHAT?
409
410A metaclass is a class that describes classes. With Moose, every class
10821858 411you define gets a C<meta()> method. It returns a L<Moose::Meta::Class>
412object, which has an introspection API that can tell you about the
413class it represents.
270df362 414
415 my $meta = User->meta();
416
417 for my $attribute ( $meta->compute_all_applicable_attributes ) {
418 print $attribute->name(), "\n";
419
420 if ( $attribute->has_type_constraint ) {
421 print " type: ", $attribute->type_constraint->name, "\n";
422 }
423 }
424
425 for my $method ( $meta->compute_all_applicable_methods ) {
426 print $method->name, "\n";
427 }
428
429Almost every concept we defined earlier has a meta class, so we have
430L<Moose::Meta::Class>, L<Moose::Meta::Attribute>,
431L<Moose::Meta::Method>, L<Moose::Meta::Role>,
432L<Moose::Meta::TypeConstraint>, L<Moose::Meta::Instance>, and so on.
433
434=head1 BUT I NEED TO DO IT MY WAY!
435
cb4abcc5 436One of the great things about Moose is that if you dig down and find
270df362 437that it does something the "wrong way", you can change it by extending
10821858 438a metaclass. For example, you can have arrayref based objects, you can
439make your constructors strict (no unknown params allowed!), you can
440define a naming scheme for attribute accessors, you can make a class a
441Singleton, and much, much more.
270df362 442
443Many of these extensions require surprisingly small amounts of code,
444and once you've done it once, you'll never have to hand-code "your way
2d244c60 445of doing things" again. Instead you'll just load your favorite
10821858 446extensions.
447
448 package MyWay::User;
449
450 use Moose;
451 use MooseX::StrictConstructor
452 use MooseX::MyWay;
453
454 has ...;
455
270df362 456
457=head1 JUSTIFICATION
458
459If you're still still asking yourself "Why do I need this?", then this
460section is for you.
461
462=over 4
463
464=item Another object system!?!?
465
466Yes, I know there has been an explosion recently of new ways to
467build objects in Perl 5, most of them based on inside-out objects
468and other such things. Moose is different because it is not a new
469object system for Perl 5, but instead an extension of the existing
470object system.
471
472Moose is built on top of L<Class::MOP>, which is a metaclass system
473for Perl 5. This means that Moose not only makes building normal
474Perl 5 objects better, but it also provides the power of metaclass
475programming.
476
477=item Is this for real? Or is this just an experiment?
478
479Moose is I<based> on the prototypes and experiments Stevan did for the
480Perl 6 meta-model. However, Moose is B<NOT> an experiment or
481prototype; it is for B<real>.
482
483=item Is this ready for use in production?
484
485Yes.
486
10821858 487Moose has been used successfully in production environments by several
270df362 488people and companies. There are Moose applications which have been in
489production with little or no issue now for well over two years. We
490consider it highly stable and we are commited to keeping it stable.
491
492Of course, in the end, you need to make this call yourself. If you
493have any questions or concerns, please feel free to email Stevan, the
494moose@perl.org list, or just stop by irc.perl.org#moose and ask away.
495
496=item Is Moose just Perl 6 in Perl 5?
497
498No. While Moose is very much inspired by Perl 6, it is not itself Perl
4996. Instead, it is an OO system for Perl 5. Stevan built Moose because
500he was tired of writing the same old boring Perl 5 OO code, and
501drooling over Perl 6 OO. So instead of switching to Ruby, he wrote
502Moose :)
503
504=item Wait, I<post> modern, I thought it was just I<modern>?
505
506Stevan read Larry Wall's talk from the 1999 Linux World entitled
507"Perl, the first postmodern computer language" in which he talks about
508how he picked the features for Perl because he thought they were cool
509and he threw out the ones that he thought sucked. This got him
510thinking about how we have done the same thing in Moose. For Moose, we
511have "borrowed" features from Perl 6, CLOS (LISP), Smalltalk, Java,
512BETA, OCaml, Ruby and more, and the bits we didn't like (cause they
513sucked) we tossed aside. So for this reason (and a few others) Stevan
514has re-dubbed Moose a I<postmodern> object system.
515
516Nuff Said.
517
518=back
519
e03c5ed2 520=head1 WHAT NEXT?
521
522So you're sold on Moose. Time to learn how to really use it.
523
524We recommend that you start with the L<Moose::Cookbook>. If you work
525your way through all the recipes under the basics section, you should
526have a pretty good sense of how Moose works, and all of its basic OO
527features.
528
529After that, check out the Role recipes. If you're really curious, go
530on and read the Meta and Extending recipes, but those are mostly there
531for people who want to be Moose wizards and change how Moose works.
532
f330de33 533If you want to see how Moose would translate directly old school Perl
d6dac1fd 5345 OO code, check out L<Moose::Unsweetened>.
f330de33 535
270df362 536=head1 AUTHOR
537
10821858 538Dave Rolsky E<lt>autarch@urth.orgE<gt> and Stevan Little
270df362 539E<lt>stevan@iinteractive.comE<gt>
540
541=head1 COPYRIGHT AND LICENSE
542
543Copyright 2008 by Infinity Interactive, Inc.
544
545L<http://www.iinteractive.com>
546
547This library is free software; you can redistribute it and/or modify
548it under the same terms as Perl itself.
549
550=cut