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.2203
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 in
191 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 will
198 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 it
206 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 accessors.
255
256 With Moose, you define types declaratively, and then use them by
257 name with your attributes.
258
259 • Delegation
260
261 "Class::Delegation" or "Class::Delegator", but probably even more
262 hand-written code.
263
264 With Moose, this is also declarative.
265
266 • Constructor
267
268 A new() method which calls "bless" on a reference.
269
270 Comes for free when you define a class with Moose.
271
272 • Destructor
273
274 A DESTROY() method.
275
276 With Moose, this is called DEMOLISH().
277
278 • Object Instance
279
280 A blessed reference, usually a hash reference.
281
282 With Moose, this is an opaque thing which has a bunch of attributes
283 and methods, as defined by its class.
284
285 • Immutabilization
286
287 Moose comes with a feature called "immutabilization". When you make
288 your class immutable, it means you're done adding methods,
289 attributes, roles, etc. This lets Moose optimize your class with a
290 bunch of extremely dirty in-place code generation tricks that speed
291 up things like object construction and so on.
292
294 A metaclass is a class that describes classes. With Moose, every class
295 you define gets a meta() method. The meta() method returns a
296 Moose::Meta::Class object, which has an introspection API that can tell
297 you about the class it represents.
298
299 my $meta = User->meta();
300
301 for my $attribute ( $meta->get_all_attributes ) {
302 print $attribute->name(), "\n";
303
304 if ( $attribute->has_type_constraint ) {
305 print " type: ", $attribute->type_constraint->name, "\n";
306 }
307 }
308
309 for my $method ( $meta->get_all_methods ) {
310 print $method->name, "\n";
311 }
312
313 Almost every concept we defined earlier has a meta class, so we have
314 Moose::Meta::Class, Moose::Meta::Attribute, Moose::Meta::Method,
315 Moose::Meta::Role, Moose::Meta::TypeConstraint, Moose::Meta::Instance,
316 and so on.
317
319 One of the great things about Moose is that if you dig down and find
320 that it does something the "wrong way", you can change it by extending
321 a metaclass. For example, you can have arrayref based objects, you can
322 make your constructors strict (no unknown parameters allowed!), you can
323 define a naming scheme for attribute accessors, you can make a class a
324 Singleton, and much, much more.
325
326 Many of these extensions require surprisingly small amounts of code,
327 and once you've done it once, you'll never have to hand-code "your way
328 of doing things" again. Instead you'll just load your favorite
329 extensions.
330
331 package MyWay::User;
332
333 use Moose;
334 use MooseX::StrictConstructor;
335 use MooseX::MyWay;
336
337 has ...;
338
340 So you're sold on Moose. Time to learn how to really use it.
341
342 If you want to see how Moose would translate directly into old school
343 Perl 5 OO code, check out Moose::Manual::Unsweetened. This might be
344 helpful for quickly wrapping your brain around some aspects of "the
345 Moose way".
346
347 Or you can skip that and jump straight to Moose::Manual::Classes and
348 the rest of the Moose::Manual.
349
350 After that we recommend that you start with the Moose::Cookbook. If you
351 work your way through all the recipes under the basics section, you
352 should have a pretty good sense of how Moose works, and all of its
353 basic OO features.
354
355 After that, check out the Role recipes. If you're really curious, go on
356 and read the Meta and Extending recipes, but those are mostly there for
357 people who want to be Moose wizards and extend Moose itself.
358
360 • Stevan Little <stevan@cpan.org>
361
362 • Dave Rolsky <autarch@urth.org>
363
364 • Jesse Luehrs <doy@cpan.org>
365
366 • Shawn M Moore <sartak@cpan.org>
367
368 • יובל קוג'מן (Yuval Kogman) <nothingmuch@woobling.org>
369
370 • Karen Etheridge <ether@cpan.org>
371
372 • Florian Ragwitz <rafl@debian.org>
373
374 • Hans Dieter Pearcey <hdp@cpan.org>
375
376 • Chris Prather <chris@prather.org>
377
378 • Matt S Trout <mstrout@cpan.org>
379
381 This software is copyright (c) 2006 by Infinity Interactive, Inc.
382
383 This is free software; you can redistribute it and/or modify it under
384 the same terms as the Perl 5 programming language system itself.
385
386
387
388perl v5.36.0 2023-02-06 Moose::Manual::Concepts(3)