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