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