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