1Moose(3) User Contributed Perl Documentation Moose(3)
2
3
4
6 Moose - A complete modern object system for Perl 5
7
9 package Point;
10 use Moose; # automatically turns on strict and warnings
11
12 has 'x' => (is => 'rw', isa => 'Int');
13 has 'y' => (is => 'rw', isa => 'Int');
14
15 sub clear {
16 my $self = shift;
17 $self->x(0);
18 $self->y(0);
19 }
20
21 package Point3D;
22 use Moose;
23
24 extends 'Point';
25
26 has 'z' => (is => 'rw', isa => 'Int');
27
28 after 'clear' => sub {
29 my $self = shift;
30 $self->z(0);
31 };
32
34 Moose is an extension of the Perl 5 object system.
35
36 Another object system!?!?
37
38 Yes, I know there has been an explosion recently of new ways to build
39 object's in Perl 5, most of them based on inside-out objects and other
40 such things. Moose is different because it is not a new object system
41 for Perl 5, but instead an extension of the existing object system.
42
43 Moose is built on top of Class::MOP, which is a metaclass system for
44 Perl 5. This means that Moose not only makes building normal Perl 5
45 objects better, but it also provides the power of metaclass program‐
46 ming.
47
48 Is this for real? Or is this just an experiment?
49
50 Moose is based on the prototypes and experiments I did for the Perl 6
51 meta-model. However, Moose is NOT an experiment/prototype; it is for
52 real.
53
54 Is this ready for use in production?
55
56 Yes, I believe that it is.
57
58 Moose has been used successfully in production environemnts by several
59 people and companies (including the one I work for). There are Moose
60 applications which have been in production with little or no issue now
61 for over a year. I consider it highly stable and we are commited to
62 keeping it stable.
63
64 Of course, in the end, you need to make this call yourself. If you have
65 any questions or concerns, please feel free to email me, or even the
66 list or just stop by #moose and ask away.
67
68 Is Moose just Perl 6 in Perl 5?
69
70 No. While Moose is very much inspired by Perl 6, it is not itself Perl
71 6. Instead, it is an OO system for Perl 5. I built Moose because I was
72 tired of writing the same old boring Perl 5 OO code, and drooling over
73 Perl 6 OO. So instead of switching to Ruby, I wrote Moose :)
74
75 Moose Extensions
76
77 The MooseX:: namespace is the official place to find Moose extensions.
78 There are a number of these modules out on CPAN right now the best way
79 to find them is to search for MooseX:: on search.cpan.org.
80
82 Moose makes every attempt to provide as much convenience as possible
83 during class construction/definition, but still stay out of your way if
84 you want it to. Here are a few items to note when building classes with
85 Moose.
86
87 Unless specified with "extends", any class which uses Moose will
88 inherit from Moose::Object.
89
90 Moose will also manage all attributes (including inherited ones) that
91 are defined with "has". And (assuming you call "new", which is inher‐
92 ited from Moose::Object) this includes properly initializing all
93 instance slots, setting defaults where appropriate, and performing any
94 type constraint checking or coercion.
95
97 Moose will export a number of functions into the class's namespace
98 which may then be used to set up the class. These functions all work
99 directly on the current class.
100
101 meta
102 This is a method which provides access to the current class's meta‐
103 class.
104
105 extends (@superclasses)
106 This function will set the superclass(es) for the current class.
107
108 This approach is recommended instead of "use base", because "use
109 base" actually "push"es onto the class's @ISA, whereas "extends"
110 will replace it. This is important to ensure that classes which do
111 not have superclasses still properly inherit from Moose::Object.
112
113 with (@roles)
114 This will apply a given set of @roles to the local class. Role sup‐
115 port is currently under heavy development; see Moose::Role for more
116 details.
117
118 has $name => %options
119 This will install an attribute of a given $name into the current
120 class. The %options are the same as those provided by
121 Class::MOP::Attribute, in addition to the list below which are pro‐
122 vided by Moose (Moose::Meta::Attribute to be more specific):
123
124 is => 'rw'⎪'ro'
125 The is option accepts either rw (for read/write) or ro (for
126 read only). These will create either a read/write accessor or a
127 read-only accessor respectively, using the same name as the
128 $name of the attribute.
129
130 If you need more control over how your accessors are named, you
131 can use the reader, writer and accessor options inherited from
132 Class::MOP::Attribute.
133
134 isa => $type_name
135 The isa option uses Moose's type constraint facilities to set
136 up runtime type checking for this attribute. Moose will perform
137 the checks during class construction, and within any accessors.
138 The $type_name argument must be a string. The string may be
139 either a class name or a type defined using Moose's type defi‐
140 nition features. (Refer to Moose::Util::TypeConstraints for
141 information on how to define a new type, and how to retrieve
142 type meta-data).
143
144 coerce => (1⎪0)
145 This will attempt to use coercion with the supplied type con‐
146 straint to change the value passed into any accessors or con‐
147 structors. You must have supplied a type constraint in order
148 for this to work. See Moose::Cookbook::Recipe5 for an example.
149
150 does => $role_name
151 This will accept the name of a role which the value stored in
152 this attribute is expected to have consumed.
153
154 required => (1⎪0)
155 This marks the attribute as being required. This means a
156 defined value must be supplied during class construction, and
157 the attribute may never be set to "undef" with an accessor.
158
159 weak_ref => (1⎪0)
160 This will tell the class to store the value of this attribute
161 as a weakened reference. If an attribute is a weakened refer‐
162 ence, it cannot also be coerced.
163
164 lazy => (1⎪0)
165 This will tell the class to not create this slot until abso‐
166 lutely necessary. If an attribute is marked as lazy it must
167 have a default supplied.
168
169 auto_deref => (1⎪0)
170 This tells the accessor whether to automatically dereference
171 the value returned. This is only legal if your "isa" option is
172 either "ArrayRef" or "HashRef".
173
174 metaclass => $metaclass_name
175 This tells the class to use a custom attribute metaclass for
176 this particular attribute. Custom attribute metaclasses are
177 useful for extending the capabilities of the has keyword: they
178 are the simplest way to extend the MOP, but they are still a
179 fairly advanced topic and too much to cover here. I will try
180 and write a recipe on them soon.
181
182 The default behavior here is to just load $metaclass_name; how‐
183 ever, we also have a way to alias to a shorter name. This will
184 first look to see if Moose::Meta::Attribute::Custom::$meta‐
185 class_name exists. If it does, Moose will then check to see if
186 that has the method "register_implemenetation", which should
187 return the actual name of the custom attribute metaclass. If
188 there is no "register_implemenetation" method, it will fall
189 back to using Moose::Meta::Attribute::Custom::$metaclass_name
190 as the metaclass name.
191
192 trigger => $code
193 The trigger option is a CODE reference which will be called
194 after the value of the attribute is set. The CODE ref will be
195 passed the instance itself, the updated value and the attribute
196 meta-object (this is for more advanced fiddling and can typi‐
197 cally be ignored). You cannot have a trigger on a read-only
198 attribute.
199
200 handles => ARRAY ⎪ HASH ⎪ REGEXP ⎪ ROLE ⎪ CODE
201 The handles option provides Moose classes with automated dele‐
202 gation features. This is a pretty complex and powerful option.
203 It accepts many different option formats, each with its own
204 benefits and drawbacks.
205
206 NOTE: This feature is no longer experimental, but it may still
207 have subtle bugs lurking in the deeper corners. If you think
208 you have found a bug, you probably have, so please report it to
209 me right away.
210
211 NOTE: The class being delegated to does not need to be a Moose
212 based class, which is why this feature is especially useful
213 when wrapping non-Moose classes.
214
215 All handles option formats share the following traits:
216
217 You cannot override a locally defined method with a delegated
218 method; an exception will be thrown if you try. That is to say,
219 if you define "foo" in your class, you cannot override it with
220 a delegated "foo". This is almost never something you would
221 want to do, and if it is, you should do it by hand and not use
222 Moose.
223
224 You cannot override any of the methods found in Moose::Object,
225 or the "BUILD" and "DEMOLISH" methods. These will not throw an
226 exception, but will silently move on to the next method in the
227 list. My reasoning for this is that you would almost never want
228 to do this, since it usually breaks your class. As with over‐
229 riding locally defined methods, if you do want to do this, you
230 should do it manually, not with Moose.
231
232 You do not need to have a reader (or accessor) for the
233 attribute in order to delegate to it. Moose will create a means
234 of accessing the value for you, however this will be several
235 times less efficient then if you had given the attribute a
236 reader (or accessor) to use.
237
238 Below is the documentation for each option format:
239
240 "ARRAY"
241 This is the most common usage for handles. You basically
242 pass a list of method names to be delegated, and Moose will
243 install a delegation method for each one.
244
245 "HASH"
246 This is the second most common usage for handles. Instead
247 of a list of method names, you pass a HASH ref where each
248 key is the method name you want installed locally, and its
249 value is the name of the original method in the class being
250 delegated to.
251
252 This can be very useful for recursive classes like trees.
253 Here is a quick example (soon to be expanded into a
254 Moose::Cookbook::Recipe):
255
256 package Tree;
257 use Moose;
258
259 has 'node' => (is => 'rw', isa => 'Any');
260
261 has 'children' => (
262 is => 'ro',
263 isa => 'ArrayRef',
264 default => sub { [] }
265 );
266
267 has 'parent' => (
268 is => 'rw',
269 isa => 'Tree',
270 is_weak_ref => 1,
271 handles => {
272 parent_node => 'node',
273 siblings => 'children',
274 }
275 );
276
277 In this example, the Tree package gets "parent_node" and
278 "siblings" methods, which delegate to the "node" and "chil‐
279 dren" methods (respectively) of the Tree instance stored in
280 the "parent" slot.
281
282 "REGEXP"
283 The regexp option works very similar to the ARRAY option,
284 except that it builds the list of methods for you. It
285 starts by collecting all possible methods of the class
286 being delegated to, then filters that list using the regexp
287 supplied here.
288
289 NOTE: An isa option is required when using the regexp
290 option format. This is so that we can determine (at compile
291 time) the method list from the class. Without an isa this
292 is just not possible.
293
294 "ROLE"
295 With the role option, you specify the name of a role whose
296 "interface" then becomes the list of methods to handle. The
297 "interface" can be defined as; the methods of the role and
298 any required methods of the role. It should be noted that
299 this does not include any method modifiers or generated
300 attribute methods (which is consistent with role composi‐
301 tion).
302
303 "CODE"
304 This is the option to use when you really want to do some‐
305 thing funky. You should only use it if you really know what
306 you are doing, as it involves manual metaclass twiddling.
307
308 This takes a code reference, which should expect two argu‐
309 ments. The first is the attribute meta-object this handles
310 is attached to. The second is the metaclass of the class
311 being delegated to. It expects you to return a hash (not a
312 HASH ref) of the methods you want mapped.
313
314 has +$name => %options
315 This is variation on the normal attibute creator "has" which allows
316 you to clone and extend an attribute from a superclass. Here is a
317 quick example:
318
319 package Foo;
320 use Moose;
321
322 has 'message' => (
323 is => 'rw',
324 isa => 'Str',
325 default => 'Hello, I am a Foo'
326 );
327
328 package My::Foo;
329 use Moose;
330
331 extends 'Foo';
332
333 has '+message' => (default => 'Hello I am My::Foo');
334
335 What is happening here is that My::Foo is cloning the "message"
336 attribute from its parent class Foo, retaining the "is => 'rw'" and
337 "isa => 'Str'" characteristics, but changing the value in
338 "default".
339
340 This feature is restricted somewhat, so as to try and force at
341 least some sanity into it. You are only allowed to change the fol‐
342 lowing attributes:
343
344 default
345 Change the default value of an attribute.
346
347 coerce
348 Change whether the attribute attempts to coerce a value passed
349 to it.
350
351 required
352 Change if the attribute is required to have a value.
353
354 documentation
355 Change the documentation string associated with the attribute.
356
357 lazy
358 Change if the attribute lazily initializes the slot.
359
360 isa You are allowed to change the type, if and only if the new type
361 is a subtype of the old type.
362
363 handles
364 You are allowed to add a new "handles" definition, but you are
365 not allowed to change one.
366
367 before $name⎪@names => sub { ... }
368 after $name⎪@names => sub { ... }
369 around $name⎪@names => sub { ... }
370 This three items are syntactic sugar for the before, after, and
371 around method modifier features that Class::MOP provides. More
372 information on these may be found in the Class::MOP::Class documen‐
373 tation for now.
374
375 super
376 The keyword "super" is a no-op when called outside of an "override"
377 method. In the context of an "override" method, it will call the
378 next most appropriate superclass method with the same arguments as
379 the original method.
380
381 override ($name, &sub)
382 An "override" method is a way of explicitly saying "I am overriding
383 this method from my superclass". You can call "super" within this
384 method, and it will work as expected. The same thing can be accom‐
385 plished with a normal method call and the "SUPER::" pseudo-package;
386 it is really your choice.
387
388 inner
389 The keyword "inner", much like "super", is a no-op outside of the
390 context of an "augment" method. You can think of "inner" as being
391 the inverse of "super"; the details of how "inner" and "augment"
392 work is best described in the Moose::Cookbook.
393
394 augment ($name, &sub)
395 An "augment" method, is a way of explicitly saying "I am augmenting
396 this method from my superclass". Once again, the details of how
397 "inner" and "augment" work is best described in the Moose::Cook‐
398 book.
399
400 confess
401 This is the "Carp::confess" function, and exported here because I
402 use it all the time. This feature may change in the future, so you
403 have been warned.
404
405 blessed
406 This is the "Scalar::Util::blessed" function, it is exported here
407 because I use it all the time. It is highly recommended that this
408 is used instead of "ref" anywhere you need to test for an object's
409 class name.
410
412 unimport
413
414 Moose offers a way to remove the keywords it exports, through the
415 "unimport" method. You simply have to say "no Moose" at the bottom of
416 your code for this to work. Here is an example:
417
418 package Person;
419 use Moose;
420
421 has 'first_name' => (is => 'rw', isa => 'Str');
422 has 'last_name' => (is => 'rw', isa => 'Str');
423
424 sub full_name {
425 my $self = shift;
426 $self->first_name . ' ' . $self->last_name
427 }
428
429 no Moose; # keywords are removed from the Person package
430
432 Moose also offers some options for extending or embedding it into your
433 own framework. The basic premise is to have something that sets up your
434 class' metaclass and export the moose declarators ("has", "with",
435 "extends",...). Here is an example:
436
437 package MyFramework;
438 use Moose;
439
440 sub import {
441 my $CALLER = caller();
442
443 strict->import;
444 warnings->import;
445
446 # we should never export to main
447 return if $CALLER eq 'main';
448 Moose::init_meta( $CALLER, 'MyFramework::Base' );
449 Moose->import({into => $CALLER});
450
451 # Do my custom framework stuff
452
453 return 1;
454 }
455
456 import
457
458 Moose's "import" method supports the Sub::Exporter form of "{into =>
459 $pkg}" and "{into_level => 1}"
460
461 init_meta ($class, $baseclass, $metaclass)
462
463 Moose does some boot strapping: it creates a metaclass object for your
464 class, and then injects a "meta" accessor into your class to retrieve
465 it. Then it sets your baseclass to Moose::Object or the value you pass
466 in unless you already have one. This is all done via "init_meta" which
467 takes the name of your class and optionally a baseclass and a metaclass
468 as arguments.
469
471 · It should be noted that "super" and "inner" cannot be used in the
472 same method. However, they may be combined within the same class
473 hierarchy; see t/014_override_augment_inner_super.t for an example.
474
475 The reason for this is that "super" is only valid within a method
476 with the "override" modifier, and "inner" will never be valid
477 within an "override" method. In fact, "augment" will skip over any
478 "override" methods when searching for its appropriate "inner".
479
480 This might seem like a restriction, but I am of the opinion that
481 keeping these two features separate (yet interoperable) actually
482 makes them easy to use, since their behavior is then easier to pre‐
483 dict. Time will tell whether I am right or not (UPDATE: so far so
484 good).
485
487 I blame Sam Vilain for introducing me to the insanity that is meta-mod‐
488 els.
489 I blame Audrey Tang for then encouraging my meta-model habit in #perl6.
490 Without Yuval "nothingmuch" Kogman this module would not be possible,
491 and it certainly wouldn't have this name ;P
492 The basis of the TypeContraints module was Rob Kinyon's idea origi‐
493 nally, I just ran with it.
494 Thanks to mst & chansen and the whole #moose poose for all the early
495 ideas/feature-requests/encouragement/bug-finding.
496 Thanks to David "Theory" Wheeler for meta-discussions and spelling
497 fixes.
498
500 <http://www.iinteractive.com/moose>
501 This is the official web home of Moose, it contains links to our
502 public SVN repo as well as links to a number of talks and articles
503 on Moose and Moose related technologies.
504
505 Class::MOP documentation
506 The #moose channel on irc.perl.org
507 The Moose mailing list - moose@perl.org
508 Moose stats on ohloh.net - <http://www.ohloh.net/projects/5788>
509 Several Moose extension modules in the MooseX:: namespace.
510
511 Papers
512
513 <http://www.cs.utah.edu/plt/publications/oopsla04-gff.pdf>
514 This paper (suggested by lbr on #moose) was what lead to the imple‐
515 mentation of the "super"/"override" and "inner"/"augment" features.
516 If you really want to understand them, I suggest you read this.
517
519 All complex software has bugs lurking in it, and this module is no
520 exception. If you find a bug please either email me, or add the bug to
521 cpan-RT.
522
524 Stevan Little <stevan@iinteractive.com>
525
526 with contributions from:
527
528 Aankhen
529
530 Adam (Alias) Kennedy
531
532 Anders (Debolaz) Nor Berle
533
534 Nathan (kolibre) Gray
535
536 Christian (chansen) Hansen
537
538 Hans Dieter (confound) Pearcey
539
540 Eric (ewilhelm) Wilhelm
541
542 Guillermo (groditi) Roditi
543
544 Jess (castaway) Robinson
545
546 Matt (mst) Trout
547
548 Robert (phaylon) Sedlacek
549
550 Robert (rlb3) Boone
551
552 Scott (konobi) McWhirter
553
554 Shlomi (rindolf) Fish
555
556 Yuval (nothingmuch) Kogman
557
558 Chris (perigrin) Prather
559
560 Jonathan (jrockway) Rockway
561
562 Piotr (dexter) Roszatycki
563
564 Sam (mugwump) Vilain
565
566 ... and many other #moose folks
567
569 Copyright 2006, 2007 by Infinity Interactive, Inc.
570
571 <http://www.iinteractive.com>
572
573 This library is free software; you can redistribute it and/or modify it
574 under the same terms as Perl itself.
575
576
577
578perl v5.8.8 2007-09-06 Moose(3)