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