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