5 Moose::Intro - What is Moose, and how do I use it?
9 Moose is a I<complete> object system for Perl 5. If you've used a
10 modern object-oriented language (which Perl 5 definitely isn't),
11 you've seen seen that they provide keywords for things like attribute
12 declaration, object construction, and inheritance. These keywords are
13 part of the language, and you don't care about how they are implemented.
15 Moose aims to do the same thing for Perl 5 OO. We can't actually
16 create new keywords, but we do offer "sugar" subroutines that look a
19 Moose tries to get you thinking about the I<logical> structure of your
20 classes, rather than the underlying implementation. Your class
21 definitions are I<declarative>, focusing on "what" rather than
22 "how". With Moose, a class definition should read like a list of very
23 concise English sentences.
25 Moose is built in top of C<Class::MOP>, a meta-object protocol (aka
26 MOP). Using the MOP, Moose provides complete introspection for all
27 Moose-using classes. This means you can ask classes about their
28 attributes, parents, children, methods, etc., all using a well-defined
29 API. The MOP abstracts digging about in the Perl symbol table and
30 looking at C<@ISA> vars.
32 All of this work is based in large part on the Perl 6 object system,
33 which in turn draws from CLOS, Smalltalk, and other languages.
37 Moose makes Perl 5 OO simpler, while adding power. It encapsulates all
38 the tricks of Perl 5 power users, like symbol table manipulation, in
39 high-level declarative APIs which are easy to use, and don't require
40 any special knowledge of how Perl works under the hood.
42 Moose makes Perl 5 OO fun, accessible, and powerful. And if you want
43 to dig under the hood, Moose lets you do that too, by using and
44 extending its introspection API.
62 This is a I<complete and usable> class definition!
79 handles => { 'last_login_date' => 'date' },
86 return 0 if $pw ne $self->password;
88 $self->last_login( DateTime->now() );
93 We'll leave the line-by-line explanation of this code to other
94 documentation, but just reading it you can get a sense of what these
97 =head2 Where's the Constructor?
99 One point of confusion that might come up with Moose is how it handles
100 object construction. B<You should not define a C<new()> method for
103 Moose will provide one for you. It will accept a hash or hash
104 reference of named parameters matching your attributes. This is just
105 another way in which Moose keeps your from worrying I<how> classes are
106 implemented. Simply define a class and you're ready to start creating
109 =head1 MOOSE CONCEPT (VS "OLD SCHOOL" Perl)
111 In the past, you may not have though too much about difference between
112 packages and classes, attributes and methods, constructors vs methods,
113 etc. Part of what the MOP provides is well-defined introspection
114 features for each of those things, and in turn Moose provides
115 I<distinct> sugar for each of them. Moose also introduces concepts
116 that are uncommon (or entirely new) like roles, method modifiers, and
117 declarative delegation.
119 It is helpful to define each of these concepts the Moose way, and to
120 distinguish them from the "old school" Perl 5 OO way.
124 When you say "use Moose" in a package, you are defining your package
125 as a class. At its most simple, a class will consist of attributes
126 and/or methods. It can also include roles, method modifiers, and more.
128 A class I<has> (owns) zero or more B<attributes>.
130 A class I<has> zero or more B<methods>.
132 A class I<may have> one or more superclasses (aka parent classes). A
133 class inherits from its superclass(es).
135 A class may I<have> B<method modifiers>. These modifiers can apply to
136 its own methods or methods belonging to any of its parents.
138 A class may I<do> one or more B<roles>.
140 A class I<has> a B<constructor> and a B<destructor>, and these are
141 automatically provided for you by Moose. The constructor produces
144 A class I<has> a B<metaclass>, which in turn has B<meta-attributes>,
145 B<meta-methods>, and B<meta-roles>. This metaclass I<describes> the
148 A class is usually analogous to a category of nouns, like "People" or
153 An attribute is a property of the class that defines it. It I<always>
154 has a name, and it I<may have> a number of other properties.
156 Its properties may include it a read/write flag, a B<type>, accessor
157 method names, B<delegations>, and more.
159 Attributes I<are not> methods, but by defining them causes various
160 methods to be created. Most attributes at least have a reader
161 method. Many attributes have things like a writer method, clearer
162 method, and predicate method ("has it been set?").
164 By default, Moose stores attributes in the object instance, which is a
165 hashref, I<but this is invisible to a typical Moose-base class
166 author>! It is best to think of Moose attributes as "properties" of
167 the B<object instance> which are accessed through well-defined
170 An attribute is usually analagous to specific feature of something in
171 the class's category. For example, People have first and last
172 names. Users have passwords and last login datetimes.
176 A method is very straightforward. Any subroutine you define in your
179 Methods correspond to verbs, and are what your objects can do. For
180 example, a User can login.
184 A role is something that a class I<does>. For example, a Machine class
185 might do the Breakable role, and a so could a Bone class. A role is
186 used to define some concept that cuts across multiple unrelated
187 classes, like "breakability".
189 A role I<has> zero or more B<attributes>.
191 A role I<has> zero or more B<methods>.
193 A role I<has> zero or more B<method modifiers>.
195 A role I<has> zero or more B<required methods>.
197 A required method is not implemented by the role. Instead, a required
198 method says "to use this Role you must implement this method".
200 Roles are I<composed> into classes (or other roles). When a role is
201 composed into a class, its attributes and methods are "flattened" into
202 the class. Roles I<do not> show up in the inheritance hierarchy. When
203 a role is composed, it's attributes and methods appear as if they were
204 defined I<in the consuming class>.
206 Role are somewhat like mixins or interfaces in other OO languages.
225 =head2 Method Modifiers
227 A method modifier is a way of defining an action to be taken when a
228 named method is called. For example, you could say "before calling
229 C<login()>, call this modifier first". Modifiers come in different
230 flavors like "before", "after", "around", and "augment".
232 Method modifiers are often used as an alternative to overriding a
233 method in a parent class. They are also used in roles as a way of
234 modifying methods in the consuming class.
236 Under the hood, a method modifier is just a plain old Perl subroutine
237 that gets called before, after, etc some other method.
239 before 'login' => sub {
243 warn "Called login() with $pw\n";
248 Moose also comes with a (miniature) type system. This allows you to
249 define types for attributes. Moose has a set of built-in types based
250 on what Perl provides, such as "Str", "Num", "Bool", "HashRef", etc.
252 In addition, every class name in your application can also be used as
253 a type name. We saw an example using "DateTime" earlier.
255 Finally, you can define your own types, either as subtypes or entirely
256 new types, with their own constraints. For example, you could define a
257 btype "PosInt", a subtype of "Int" which only allows positive numbers.
261 Moose attributes provide declarative syntax for defining
262 delegations. A delegation is a method which delegates the real work to
263 some attribute of the class.
265 We saw this in the User example, where we define a delegation for the
266 C<last_login_date()> method. Under the hood, this simple calls
267 C<date()> on the User object's C<last_login_datetime> attribute.
271 A constructor creates an B<object instance> for the class. In old
272 school Perl, this was usually done by defining a method called
273 C<new()> which in turn called C<bless> on a reference.
275 With Moose, this C<new()> method is created for you, and it simply
276 does the right thing. You should never need to define your own
281 This is a special method called when an object instance goes out of
282 scope. You can specialize what your class does in this method if you
283 need to, but you usually don't.
285 With old school Perl 5, this is the C<DESTROY()> method, but with
286 Moose it is the C<DEMOLISH()> method.
288 =head2 Object Instance
290 An object instance is a specific noun in the class's "category". For
291 example, one specific Person or User. An instance is created by the
292 class's B<constructor>.
294 An instance has values for its attributes. For example, a specific
295 person has a first and last name,
297 In old school Perl 5, this is often a blessed hash reference. With
298 Moose, you should never need to know what your object instance
299 actually is. (ok, it's usually a blessed hashref with Moose too)
301 =head2 Moose VS Old School Summary
307 A package with no introspection other than mucking about in the symbol
310 With Moose, you get well-defined declaration and introspection.
312 =item * Moose attributes
314 Hand-written accessor methods, symbol table hackery, or a helper
315 module like C<Class::Accessor>.
317 With Moose, these are declaritively defined, and distinct from
322 These are pretty much the same in Moose.
326 C<Class::Trait> or C<Class::Role>, or maybe C<mixin.pm>.
328 With Moose, they're part of the core feature set, and are
329 introspectable like everything else.
331 =item * Method Modifiers
333 Could only be done through serious symbol table wizardry, and you
334 probably never saw this before (at least in Perl 5).
338 Hand-written parameter checking in your C<new()> method and accessors.
340 With Moose, you define types declaratively, and then use them by name
345 C<Class::Delegation> or C<Class::Delegator>, but probably even more
348 With Moose, this is also declarative.
352 A C<new()> method which calls C<bless> on a reference.
354 Comes for free when you define a class with moose.
358 A C<DESTROY()> method.
360 With Moose, this is called C<DEMOLISH()>.
362 =item * Object Instance
364 A blessed reference, usually a hash reference.
366 With Moose, this is an opaque thing which has a bunch of attributes
367 and methods, as defined by its class.
373 A metaclass is a class that describes classes. With Moose, every class
374 you define gets a C<meta()> method that you can call on the
375 class. This returns a L<Moose::Meta::Class> object, which has an
376 introspection API that can tell you about the class it represents.
378 my $meta = User->meta();
380 for my $attribute ( $meta->compute_all_applicable_attributes ) {
381 print $attribute->name(), "\n";
383 if ( $attribute->has_type_constraint ) {
384 print " type: ", $attribute->type_constraint->name, "\n";
388 for my $method ( $meta->compute_all_applicable_methods ) {
389 print $method->name, "\n";
392 Almost every concept we defined earlier has a meta class, so we have
393 L<Moose::Meta::Class>, L<Moose::Meta::Attribute>,
394 L<Moose::Meta::Method>, L<Moose::Meta::Role>,
395 L<Moose::Meta::TypeConstraint>, L<Moose::Meta::Instance>, and so on.
397 =head1 BUT I NEED TO DO IT MY WAY!
399 One of the great things about Moose, is that if you dig down and find
400 that it does something the "wrong way", you can change it by extending
401 its metaclasses. For example, you can have arrayref based objects, you
402 can add your own types, you can make your constructors strict, you can
403 define a naming scheme for attribute accessors, and much, much more.
405 Many of these extensions require surprisingly small amounts of code,
406 and once you've done it once, you'll never have to hand-code "your way
407 of doing things" again.
411 If you're still still asking yourself "Why do I need this?", then this
416 =item Another object system!?!?
418 Yes, I know there has been an explosion recently of new ways to
419 build objects in Perl 5, most of them based on inside-out objects
420 and other such things. Moose is different because it is not a new
421 object system for Perl 5, but instead an extension of the existing
424 Moose is built on top of L<Class::MOP>, which is a metaclass system
425 for Perl 5. This means that Moose not only makes building normal
426 Perl 5 objects better, but it also provides the power of metaclass
429 =item Is this for real? Or is this just an experiment?
431 Moose is I<based> on the prototypes and experiments Stevan did for the
432 Perl 6 meta-model. However, Moose is B<NOT> an experiment or
433 prototype; it is for B<real>.
435 =item Is this ready for use in production?
439 Moose has been used successfully in production environemnts by several
440 people and companies. There are Moose applications which have been in
441 production with little or no issue now for well over two years. We
442 consider it highly stable and we are commited to keeping it stable.
444 Of course, in the end, you need to make this call yourself. If you
445 have any questions or concerns, please feel free to email Stevan, the
446 moose@perl.org list, or just stop by irc.perl.org#moose and ask away.
448 =item Is Moose just Perl 6 in Perl 5?
450 No. While Moose is very much inspired by Perl 6, it is not itself Perl
451 6. Instead, it is an OO system for Perl 5. Stevan built Moose because
452 he was tired of writing the same old boring Perl 5 OO code, and
453 drooling over Perl 6 OO. So instead of switching to Ruby, he wrote
456 =item Wait, I<post> modern, I thought it was just I<modern>?
458 Stevan read Larry Wall's talk from the 1999 Linux World entitled
459 "Perl, the first postmodern computer language" in which he talks about
460 how he picked the features for Perl because he thought they were cool
461 and he threw out the ones that he thought sucked. This got him
462 thinking about how we have done the same thing in Moose. For Moose, we
463 have "borrowed" features from Perl 6, CLOS (LISP), Smalltalk, Java,
464 BETA, OCaml, Ruby and more, and the bits we didn't like (cause they
465 sucked) we tossed aside. So for this reason (and a few others) Stevan
466 has re-dubbed Moose a I<postmodern> object system.
474 Dave Rolsky E<lt>autarch@urth.orgE<gt> and Stevan Little Stevan Little
475 E<lt>stevan@iinteractive.comE<gt>
477 =head1 COPYRIGHT AND LICENSE
479 Copyright 2008 by Infinity Interactive, Inc.
481 L<http://www.iinteractive.com>
483 This library is free software; you can redistribute it and/or modify
484 it under the same terms as Perl itself.