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