f429aa2541b8de860a3a618a25d343c8d7d0cb97
[gitmo/Moose.git] / lib / Moose / Manual / Concepts.pod
1 =pod
2
3 =head1 NAME
4
5 Moose::Manual::Concepts - Moose OO Concepts
6
7 =head1 MOOSE CONCEPTS (VS "OLD SCHOOL" Perl)
8
9 In the past, you may not have thought too much about the difference
10 between packages and classes, attributes and methods, constructors and
11 methods, etc. Part of what the MOP provides is well-defined
12 introspection features for each of those things, and in turn Moose
13 provides I<distinct> sugar for each of them. Moose also introduces
14 concepts that are uncommon (or entirely new) like roles, method
15 modifiers, and declarative delegation.
16
17 Knowing what these concepts mean in Moose-speak, and how they used to
18 be done in old school Perl 5 OO is a good way to start learning to use
19 Moose.
20
21 =head2 Class
22
23 When you say "use Moose" in a package, you are defining your package
24 as a class. At its simplest, a class will consist simply of attributes
25 and/or methods. It can also include roles, method modifiers, and more.
26
27 A class I<has> zero or more B<attributes>.
28
29 A class I<has> zero or more B<methods>.
30
31 A class I<has> zero or more superclasses (aka parent classes). A
32 class inherits from its superclass(es).
33
34 A class I<has> zero or more B<method modifiers>. These modifiers can
35 apply to its own methods or methods that are inherited from its
36 ancestors.
37
38 A class I<does> zero or more B<roles>.
39
40 A class I<has> a B<constructor> and a B<destructor>. These are
41 provided for you "for free" by Moose.
42
43 The B<constructor> accepts named parameters corresponding to the
44 class's attributes and uses them to initialize an B<object instance>.
45
46 A class I<has> a B<metaclass>, which in turn has B<meta-attributes>,
47 B<meta-methods>, and B<meta-roles>. This metaclass I<describes> the
48 class.
49
50 A class is usually analogous to a category of nouns, like "People" or
51 "Users".
52
53   package Person;
54
55   use Moose;
56   # now it's a Moose class!
57
58 =head2 Attribute
59
60 An attribute is a property of the class that defines it. It I<always>
61 has a name, and it I<may have> a number of other defining
62 characteristics.
63
64 These characteristics may include a read/write flag, a B<type>,
65 accessor method names, B<delegations>, a default value, and more.
66
67 Attributes I<are not> methods, but defining them causes various
68 accessor methods to be created. At a minimum, a normal attribute will
69 always have a reader accessor method. Many attributes have things like
70 a writer method, clearer method, and predicate method ("has it been
71 set?").
72
73 An attribute may also define B<delegation>s, which will create
74 additional methods based on the delegation specification.
75
76 By default, Moose stores attributes in the object instance, which is a
77 hashref, I<but this is invisible to the author of a Moose-base class>!
78 It is best to think of Moose attributes as "properties" of the
79 I<opaque> B<object instance>. These properties are accessed through
80 well-defined accessor methods.
81
82 An attribute is usually analogous to a specific feature of something in
83 the class's category. For example, People have first and last
84 names. Users have passwords and last login datetimes.
85
86   has 'first_name' => (
87       is  => 'rw',
88       isa => 'Str',
89   );
90
91 =head2 Method
92
93 A method is very straightforward. Any subroutine you define in your
94 class is a method.
95
96 Methods correspond to verbs, and are what your objects can do. For
97 example, a User can login.
98
99   sub login { ... }
100
101 =head2 Roles
102
103 A role is something that a class I<does>. For example, a Machine class
104 might do the Breakable role, and so could a Bone class. A role is
105 used to define some concept that cuts across multiple unrelated
106 classes, like "breakability", or "has a color".
107
108 A role I<has> zero or more B<attributes>.
109
110 A role I<has> zero or more B<methods>.
111
112 A role I<has> zero or more B<method modifiers>.
113
114 A role I<has> zero or more B<required methods>.
115
116 A required method is not implemented by the role. Instead, a required
117 method says "to use this Role you must implement this method".
118
119 Roles are I<composed> into classes (or other roles). When a role is
120 composed into a class, its attributes and methods are "flattened" into
121 the class. Roles I<do not> show up in the inheritance hierarchy. When
122 a role is composed, its attributes and methods appear as if they were
123 defined I<in the consuming class>.
124
125 Role are somewhat like mixins or interfaces in other OO languages.
126
127   package Breakable;
128
129   use Moose::Role;
130
131   has is_broken => (
132       is  => 'rw',
133       isa => 'Bool',
134   );
135
136   requires 'break';
137
138   before 'break' => {
139       my $self = shift;
140
141       $self->is_broken(1);
142   };
143
144 =head2 Method Modifiers
145
146 A method modifier is a way of defining an action to be taken when a
147 named method is called. Think of it as a hook on the named method. For
148 example, you could say "before calling C<login()>, call this modifier
149 first". Modifiers come in different flavors like "before", "after",
150 "around", and "augment", and you can apply more than one modifier to
151 a single method.
152
153 Method modifiers are often used as an alternative to overriding a
154 method in a parent class. They are also used in roles as a way of
155 modifying methods in the consuming class.
156
157 Under the hood, a method modifier is just a plain old Perl subroutine
158 that gets called before or after (or around, etc.) some named method.
159
160   before 'login' => sub {
161       my $self = shift;
162       my $pw   = shift;
163
164       warn "Called login() with $pw\n";
165   };
166
167 =head2 Type
168
169 Moose also comes with a (miniature) type system. This allows you to
170 define types for attributes. Moose has a set of built-in types based
171 on what Perl provides, such as "Str", "Num", "Bool", "HashRef", etc.
172
173 In addition, every class name in your application can also be used as
174 a type name. We saw an example using "DateTime" earlier.
175
176 Finally, you can define your own types, either as subtypes or entirely
177 new types, with their own constraints. For example, you could define a
178 type "PosInt", a subtype of "Int" which only allows positive numbers.
179
180 =head2 Delegation
181
182 Moose attributes provide declarative syntax for defining
183 delegations. A delegation is a method which delegates the real work to
184 some attribute of the class.
185
186 You saw this in the User example, where we defined a delegation for
187 the C<date_of_last_login()> method. Under the hood, this simple calls
188 C<date()> on the User object's C<last_login> attribute.
189
190 =head2 Constructor
191
192 A constructor creates an B<object instance> for the class. In old
193 school Perl, this was usually done by defining a method called
194 C<new()> which in turn called C<bless> on a reference.
195
196 With Moose, this C<new()> method is created for you, and it simply
197 does the right thing. You should never need to define your own
198 constructor!
199
200 Sometimes you want to do something whenever an object is created. In
201 those cases, you can provide a C<BUILD()> method in your class. Moose
202 will call this for you after creating a new object.
203
204 =head2 Destructor
205
206 This is a special method called when an object instance goes out of
207 scope. You can specialize what your class does in this method if you
208 need to, but you usually don't.
209
210 With old school Perl 5, this is the C<DESTROY()> method, but with
211 Moose it is the C<DEMOLISH()> method.
212
213 =head2 Object Instance
214
215 An object instance is a specific noun in the class's "category". For
216 example, one specific Person or User. An instance is created by the
217 class's B<constructor>.
218
219 An instance has values for its attributes. For example, a specific
220 person has a first and last name.
221
222 In old school Perl 5, this is often a blessed hash reference. With
223 Moose, you should never need to know what your object instance
224 actually is. (ok, it's usually a blessed hashref with Moose too)
225
226 =head2 Moose VS Old School Summary
227
228 =over 4
229
230 =item * Class
231
232 A package with no introspection other than mucking about in the symbol
233 table.
234
235 With Moose, you get well-defined declaration and introspection.
236
237 =item * Attributes
238
239 Hand-written accessor methods, symbol table hackery, or a helper
240 module like C<Class::Accessor>.
241
242 With Moose, these are declaratively defined, and distinct from
243 methods.
244
245 =item * Method
246
247 These are pretty much the same in Moose as in old school Perl.
248
249 =item * Roles
250
251 C<Class::Trait> or C<Class::Role>, or maybe C<mixin.pm>.
252
253 With Moose, they're part of the core feature set, and are
254 introspectable like everything else.
255
256 =item * Method Modifiers
257
258 Could only be done through serious symbol table wizardry, and you
259 probably never saw this before (at least in Perl 5).
260
261 =item * Type
262
263 Hand-written parameter checking in your C<new()> method and accessors.
264
265 With Moose, you define types declaratively, and then use them by name
266 in your attributes.
267
268 =item * Delegation
269
270 C<Class::Delegation> or C<Class::Delegator>, but probably even more
271 hand-written code.
272
273 With Moose, this is also declarative.
274
275 =item * Constructor
276
277 A C<new()> method which calls C<bless> on a reference.
278
279 Comes for free when you define a class with Moose.
280
281 =item * Destructor
282
283 A C<DESTROY()> method.
284
285 With Moose, this is called C<DEMOLISH()>.
286
287 =item * Object Instance
288
289 A blessed reference, usually a hash reference.
290
291 With Moose, this is an opaque thing which has a bunch of attributes
292 and methods, as defined by its class.
293
294 =item * Immutabilization
295
296 Moose comes with a feature called "immutabilization". When you make
297 your class immutable, it means you're done adding methods, attributes,
298 roles, etc. This lets Moose optimize your class with a bunch of
299 extremely dirty in-place code generation tricks that speed up things
300 like object construction and so on.
301
302 =back
303
304 =head1 META WHAT?
305
306 A metaclass is a class that describes classes. With Moose, every class
307 you define gets a C<meta()> method. It returns a L<Moose::Meta::Class>
308 object, which has an introspection API that can tell you about the
309 class it represents.
310
311   my $meta = User->meta();
312
313   for my $attribute ( $meta->compute_all_applicable_attributes ) {
314       print $attribute->name(), "\n";
315
316       if ( $attribute->has_type_constraint ) {
317           print "  type: ", $attribute->type_constraint->name, "\n";
318       }
319   }
320
321   for my $method ( $meta->compute_all_applicable_methods ) {
322       print $method->name, "\n";
323   }
324
325 Almost every concept we defined earlier has a meta class, so we have
326 L<Moose::Meta::Class>, L<Moose::Meta::Attribute>,
327 L<Moose::Meta::Method>, L<Moose::Meta::Role>,
328 L<Moose::Meta::TypeConstraint>, L<Moose::Meta::Instance>, and so on.
329
330 =head1 BUT I NEED TO DO IT MY WAY!
331
332 One of the great things about Moose is that if you dig down and find
333 that it does something the "wrong way", you can change it by extending
334 a metaclass. For example, you can have arrayref based objects, you can
335 make your constructors strict (no unknown params allowed!), you can
336 define a naming scheme for attribute accessors, you can make a class a
337 Singleton, and much, much more.
338
339 Many of these extensions require surprisingly small amounts of code,
340 and once you've done it once, you'll never have to hand-code "your way
341 of doing things" again. Instead you'll just load your favorite
342 extensions.
343
344   package MyWay::User;
345
346   use Moose;
347   use MooseX::StrictConstructor
348   use MooseX::MyWay;
349
350   has ...;
351
352 =head1 WHAT NEXT?
353
354 So you're sold on Moose. Time to learn how to really use it.
355
356 If you want to see how Moose would translate directly old school Perl
357 5 OO code, check out L<Moose::Unsweetened>. This might be helpful for
358 quickly wrapping your brain around some aspects of "the Moose way".
359
360 Obviously, the first thing to read is the L<Moose::Manual>
361
362 After that we recommend that you start with the L<Moose::Cookbook>. If
363 you work your way through all the recipes under the basics section,
364 you should have a pretty good sense of how Moose works, and all of its
365 basic OO features.
366
367 After that, check out the Role recipes. If you're really curious, go
368 on and read the Meta and Extending recipes, but those are mostly there
369 for people who want to be Moose wizards and change how Moose works.
370
371 =head1 AUTHOR
372
373 Dave Rolsky E<lt>autarch@urth.orgE<gt>
374
375 =head1 COPYRIGHT AND LICENSE
376
377 Copyright 2008 by Infinity Interactive, Inc.
378
379 L<http://www.iinteractive.com>
380
381 This library is free software; you can redistribute it and/or modify
382 it under the same terms as Perl itself.
383
384 =cut
385