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