This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
Move more URLs from http:// to https://
[perl5.git] / pod / perlootut.pod
CommitLineData
dbfe2941
DR
1=encoding utf8
2
3=for comment
4Consistent formatting of this file is achieved with:
5 perl ./Porting/podtidy pod/perlootut.pod
6
7=head1 NAME
8
9perlootut - Object-Oriented Programming in Perl Tutorial
10
11=head1 DATE
12
134d6544
DR
13This document was created in February, 2011, and the last major
14revision was in February, 2013.
15
16If you are reading this in the future then it's possible that the state
17of the art has changed. We recommend you start by reading the perlootut
18document in the latest stable release of Perl, rather than this
19version.
dbfe2941
DR
20
21=head1 DESCRIPTION
22
23This document provides an introduction to object-oriented programming
24in Perl. It begins with a brief overview of the concepts behind object
25oriented design. Then it introduces several different OO systems from
71c89d21 26L<CPAN|https://search.cpan.org> which build on top of what Perl
dbfe2941
DR
27provides.
28
29By default, Perl's built-in OO system is very minimal, leaving you to
30do most of the work. This minimalism made a lot of sense in 1994, but
31in the years since Perl 5.0 we've seen a number of common patterns
32emerge in Perl OO. Fortunately, Perl's flexibility has allowed a rich
33ecosystem of Perl OO systems to flourish.
34
35If you want to know how Perl OO works under the hood, the L<perlobj>
36document explains the nitty gritty details.
37
38This document assumes that you already understand the basics of Perl
39syntax, variable types, operators, and subroutine calls. If you don't
40understand these concepts yet, please read L<perlintro> first. You
41should also read the L<perlsyn>, L<perlop>, and L<perlsub> documents.
42
43=head1 OBJECT-ORIENTED FUNDAMENTALS
44
45Most object systems share a number of common concepts. You've probably
46heard terms like "class", "object, "method", and "attribute" before.
47Understanding the concepts will make it much easier to read and write
48object-oriented code. If you're already familiar with these terms, you
49should still skim this section, since it explains each concept in terms
50of Perl's OO implementation.
51
52Perl's OO system is class-based. Class-based OO is fairly common. It's
53used by Java, C++, C#, Python, Ruby, and many other languages. There
54are other object orientation paradigms as well. JavaScript is the most
55popular language to use another paradigm. JavaScript's OO system is
56prototype-based.
57
58=head2 Object
59
60An B<object> is a data structure that bundles together data and
61subroutines which operate on that data. An object's data is called
62B<attributes>, and its subroutines are called B<methods>. An object can
63be thought of as a noun (a person, a web service, a computer).
64
d49ecf98 65An object represents a single discrete thing. For example, an object
37fc2a72
DR
66might represent a file. The attributes for a file object might include
67its path, content, and last modification time. If we created an object
68to represent F</etc/hostname> on a machine named "foo.example.com",
69that object's path would be "/etc/hostname", its content would be
70"foo\n", and it's last modification time would be 1304974868 seconds
71since the beginning of the epoch.
dbfe2941 72
37fc2a72
DR
73The methods associated with a file might include C<rename()> and
74C<write()>.
dbfe2941 75
235f4381
DC
76In Perl most objects are hashes, but the OO systems we recommend keep
77you from having to worry about this. In practice, it's best to consider
78an object's internal data structure opaque.
dbfe2941
DR
79
80=head2 Class
81
82A B<class> defines the behavior of a category of objects. A class is a
37fc2a72 83name for a category (like "File"), and a class also defines the
dbfe2941
DR
84behavior of objects in that category.
85
37fc2a72
DR
86All objects belong to a specific class. For example, our
87F</etc/hostname> object belongs to the C<File> class. When we want to
88create a specific object, we start with its class, and B<construct> or
dbfe2941
DR
89B<instantiate> an object. A specific object is often referred to as an
90B<instance> of a class.
91
92In Perl, any package can be a class. The difference between a package
93which is a class and one which isn't is based on how the package is
37fc2a72 94used. Here's our "class declaration" for the C<File> class:
dbfe2941 95
37fc2a72 96 package File;
dbfe2941
DR
97
98In Perl, there is no special keyword for constructing an object.
99However, most OO modules on CPAN use a method named C<new()> to
100construct a new object:
101
37fc2a72
DR
102 my $hostname = File->new(
103 path => '/etc/hostname',
104 content => "foo\n",
105 last_mod_time => 1304974868,
dbfe2941
DR
106 );
107
108(Don't worry about that C<< -> >> operator, it will be explained
109later.)
110
111=head3 Blessing
112
235f4381
DC
113As we said earlier, most Perl objects are hashes, but an object can be
114an instance of any Perl data type (scalar, array, etc.). Turning a
115plain data structure into an object is done by B<blessing> that data
116structure using Perl's C<bless> function.
dbfe2941
DR
117
118While we strongly suggest you don't build your objects from scratch,
235f4381
DC
119you should know the term B<bless>. A B<blessed> data structure (aka "a
120referent") is an object. We sometimes say that an object has been
121"blessed into a class".
dbfe2941 122
235f4381 123Once a referent has been blessed, the C<blessed> function from the
dbfe2941
DR
124L<Scalar::Util> core module can tell us its class name. This subroutine
125returns an object's class when passed an object, and false otherwise.
126
127 use Scalar::Util 'blessed';
128
37fc2a72
DR
129 print blessed($hash); # undef
130 print blessed($hostname); # File
dbfe2941
DR
131
132=head3 Constructor
133
134A B<constructor> creates a new object. In Perl, a class's constructor
135is just another method, unlike some other languages, which provide
136syntax for constructors. Most Perl classes use C<new> as the name for
137their constructor:
138
37fc2a72 139 my $file = File->new(...);
dbfe2941
DR
140
141=head2 Methods
142
143You already learned that a B<method> is a subroutine that operates on
610e352c 144an object. You can think of a method as the things that an object can
4c054e89
DR
145I<do>. If an object is a noun, then methods are its verbs (save, print,
146open).
dbfe2941
DR
147
148In Perl, methods are simply subroutines that live in a class's package.
149Methods are always written to receive the object as their first
150argument:
151
37fc2a72 152 sub print_info {
dbfe2941
DR
153 my $self = shift;
154
37fc2a72 155 print "This file is at ", $self->path, "\n";
dbfe2941
DR
156 }
157
a6d49569 158 $file->print_info;
37fc2a72 159 # The file is at /etc/hostname
dbfe2941
DR
160
161What makes a method special is I<how it's called>. The arrow operator
162(C<< -> >>) tells Perl that we are calling a method.
163
164When we make a method call, Perl arranges for the method's B<invocant>
165to be passed as the first argument. B<Invocant> is a fancy name for the
166thing on the left side of the arrow. The invocant can either be a class
167name or an object. We can also pass additional arguments to the method:
168
37fc2a72
DR
169 sub print_info {
170 my $self = shift;
171 my $prefix = shift // "This file is at ";
dbfe2941 172
37fc2a72 173 print $prefix, ", ", $self->path, "\n";
dbfe2941
DR
174 }
175
a6d49569 176 $file->print_info("The file is located at ");
37fc2a72 177 # The file is located at /etc/hostname
dbfe2941
DR
178
179=head2 Attributes
180
181Each class can define its B<attributes>. When we instantiate an object,
37fc2a72
DR
182we assign values to those attributes. For example, every C<File> object
183has a path. Attributes are sometimes called B<properties>.
dbfe2941
DR
184
185Perl has no special syntax for attributes. Under the hood, attributes
235f4381 186are often stored as keys in the object's underlying hash, but don't
dbfe2941
DR
187worry about this.
188
189We recommend that you only access attributes via B<accessor> methods.
190These are methods that can get or set the value of each attribute. We
37fc2a72
DR
191saw this earlier in the C<print_info()> example, which calls C<<
192$self->path >>.
dbfe2941
DR
193
194You might also see the terms B<getter> and B<setter>. These are two
195types of accessors. A getter gets the attribute's value, while a setter
3282575c 196sets it. Another term for a setter is B<mutator>
dbfe2941
DR
197
198Attributes are typically defined as read-only or read-write. Read-only
199attributes can only be set when the object is first created, while
200read-write attributes can be altered at any time.
201
202The value of an attribute may itself be another object. For example,
37fc2a72
DR
203instead of returning its last mod time as a number, the C<File> class
204could return a L<DateTime> object representing that value.
dbfe2941
DR
205
206It's possible to have a class that does not expose any publicly
207settable attributes. Not every class has attributes and methods.
208
209=head2 Polymorphism
210
211B<Polymorphism> is a fancy way of saying that objects from two
37fc2a72
DR
212different classes share an API. For example, we could have C<File> and
213C<WebPage> classes which both have a C<print_content()> method. This
610e352c
DR
214method might produce different output for each class, but they share a
215common interface.
dbfe2941
DR
216
217While the two classes may differ in many ways, when it comes to the
37fc2a72
DR
218C<print_content()> method, they are the same. This means that we can
219try to call the C<print_content()> method on an object of either class,
220and B<we don't have to know what class the object belongs to!>
dbfe2941
DR
221
222Polymorphism is one of the key concepts of object-oriented design.
223
224=head2 Inheritance
225
610e352c 226B<Inheritance> lets you create a specialized version of an existing
27ffaccd
DR
227class. Inheritance lets the new class reuse the methods and attributes
228of another class.
dbfe2941 229
37fc2a72
DR
230For example, we could create an C<File::MP3> class which B<inherits>
231from C<File>. An C<File::MP3> B<is-a> I<more specific> type of C<File>.
232All mp3 files are files, but not all files are mp3 files.
dbfe2941 233
610e352c 234We often refer to inheritance relationships as B<parent-child> or
10e32c8d
DR
235C<superclass>/C<subclass> relationships. Sometimes we say that the
236child has an B<is-a> relationship with its parent class.
610e352c 237
37fc2a72
DR
238C<File> is a B<superclass> of C<File::MP3>, and C<File::MP3> is a
239B<subclass> of C<File>.
dbfe2941 240
37fc2a72 241 package File::MP3;
dbfe2941 242
37fc2a72 243 use parent 'File';
dbfe2941
DR
244
245The L<parent> module is one of several ways that Perl lets you define
246inheritance relationships.
247
248Perl allows multiple inheritance, which means that a class can inherit
249from multiple parents. While this is possible, we strongly recommend
250against it. Generally, you can use B<roles> to do everything you can do
610e352c 251with multiple inheritance, but in a cleaner way.
dbfe2941
DR
252
253Note that there's nothing wrong with defining multiple subclasses of a
254given class. This is both common and safe. For example, we might define
37fc2a72
DR
255C<File::MP3::FixedBitrate> and C<File::MP3::VariableBitrate> classes to
256distinguish between different types of mp3 file.
dbfe2941
DR
257
258=head3 Overriding methods and method resolution
259
260Inheritance allows two classes to share code. By default, every method
261in the parent class is also available in the child. The child can
262explicitly B<override> a parent's method to provide its own
37fc2a72
DR
263implementation. For example, if we have an C<File::MP3> object, it has
264the C<print_info()> method from C<File>:
265
266 my $cage = File::MP3->new(
267 path => 'mp3s/My-Body-Is-a-Cage.mp3',
268 content => $mp3_data,
269 last_mod_time => 1304974868,
270 title => 'My Body Is a Cage',
dbfe2941
DR
271 );
272
37fc2a72
DR
273 $cage->print_info;
274 # The file is at mp3s/My-Body-Is-a-Cage.mp3
dbfe2941 275
37fc2a72
DR
276If we wanted to include the mp3's title in the greeting, we could
277override the method:
dbfe2941 278
37fc2a72 279 package File::MP3;
dbfe2941 280
37fc2a72 281 use parent 'File';
dbfe2941 282
37fc2a72 283 sub print_info {
dbfe2941
DR
284 my $self = shift;
285
37fc2a72
DR
286 print "This file is at ", $self->path, "\n";
287 print "Its title is ", $self->title, "\n";
dbfe2941
DR
288 }
289
37fc2a72
DR
290 $cage->print_info;
291 # The file is at mp3s/My-Body-Is-a-Cage.mp3
292 # Its title is My Body Is a Cage
dbfe2941
DR
293
294The process of determining what method should be used is called
295B<method resolution>. What Perl does is look at the object's class
37fc2a72 296first (C<File::MP3> in this case). If that class defines the method,
dbfe2941 297then that class's version of the method is called. If not, Perl looks
37fc2a72
DR
298at each parent class in turn. For C<File::MP3>, its only parent is
299C<File>. If C<File::MP3> does not define the method, but C<File> does,
300then Perl calls the method in C<File>.
dbfe2941 301
37fc2a72 302If C<File> inherited from C<DataSource>, which inherited from C<Thing>,
dbfe2941
DR
303then Perl would keep looking "up the chain" if necessary.
304
305It is possible to explicitly call a parent method from a child:
306
37fc2a72 307 package File::MP3;
dbfe2941 308
37fc2a72 309 use parent 'File';
dbfe2941 310
37fc2a72 311 sub print_info {
dbfe2941
DR
312 my $self = shift;
313
37fc2a72
DR
314 $self->SUPER::print_info();
315 print "Its title is ", $self->title, "\n";
dbfe2941
DR
316 }
317
37fc2a72
DR
318The C<SUPER::> bit tells Perl to look for the C<print_info()> in the
319C<File::MP3> class's inheritance chain. When it finds the parent class
320that implements this method, the method is called.
dbfe2941
DR
321
322We mentioned multiple inheritance earlier. The main problem with
323multiple inheritance is that it greatly complicates method resolution.
324See L<perlobj> for more details.
325
326=head2 Encapsulation
327
328B<Encapsulation> is the idea that an object is opaque. When another
329developer uses your class, they don't need to know I<how> it is
330implemented, they just need to know I<what> it does.
331
332Encapsulation is important for several reasons. First, it allows you to
333separate the public API from the private implementation. This means you
334can change that implementation without breaking the API.
335
336Second, when classes are well encapsulated, they become easier to
337subclass. Ideally, a subclass uses the same APIs to access object data
338that its parent class uses. In reality, subclassing sometimes involves
339violating encapsulation, but a good API can minimize the need to do
340this.
341
235f4381
DC
342We mentioned earlier that most Perl objects are implemented as hashes
343under the hood. The principle of encapsulation tells us that we should
344not rely on this. Instead, we should use accessor methods to access the
345data in that hash. The object systems that we recommend below all
346automate the generation of accessor methods. If you use one of them,
347you should never have to access the object as a hash directly.
dbfe2941
DR
348
349=head2 Composition
350
351In object-oriented code, we often find that one object references
352another object. This is called B<composition>, or a B<has-a>
353relationship.
354
37fc2a72
DR
355Earlier, we mentioned that the C<File> class's C<last_mod_time>
356accessor could return a L<DateTime> object. This is a perfect example
357of composition. We could go even further, and make the C<path> and
358C<content> accessors return objects as well. The C<File> class would
d49ecf98 359then be B<composed> of several other objects.
dbfe2941
DR
360
361=head2 Roles
362
363B<Roles> are something that a class I<does>, rather than something that
364it I<is>. Roles are relatively new to Perl, but have become rather
365popular. Roles are B<applied> to classes. Sometimes we say that classes
366B<consume> roles.
367
368Roles are an alternative to inheritance for providing polymorphism.
369Let's assume we have two classes, C<Radio> and C<Computer>. Both of
370these things have on/off switches. We want to model that in our class
371definitions.
372
373We could have both classes inherit from a common parent, like
374C<Machine>, but not all machines have on/off switches. We could create
375a parent class called C<HasOnOffSwitch>, but that is very artificial.
376Radios and computers are not specializations of this parent. This
377parent is really a rather ridiculous creation.
378
379This is where roles come in. It makes a lot of sense to create a
380C<HasOnOffSwitch> role and apply it to both classes. This role would
381define a known API like providing C<turn_on()> and C<turn_off()>
382methods.
383
384Perl does not have any built-in way to express roles. In the past,
385people just bit the bullet and used multiple inheritance. Nowadays,
386there are several good choices on CPAN for using roles.
387
ce843b44
DR
388=head2 When to Use OO
389
390Object Orientation is not the best solution to every problem. In I<Perl
391Best Practices> (copyright 2004, Published by O'Reilly Media, Inc.),
392Damian Conway provides a list of criteria to use when deciding if OO is
393the right fit for your problem:
394
395=over 4
396
995ab4ef 397=item *
ce843b44
DR
398
399The system being designed is large, or is likely to become large.
400
995ab4ef 401=item *
ce843b44
DR
402
403The data can be aggregated into obvious structures, especially if
404there's a large amount of data in each aggregate.
405
995ab4ef 406=item *
ce843b44
DR
407
408The various types of data aggregate form a natural hierarchy that
409facilitates the use of inheritance and polymorphism.
410
995ab4ef 411=item *
ce843b44
DR
412
413You have a piece of data on which many different operations are
414applied.
415
995ab4ef 416=item *
ce843b44
DR
417
418You need to perform the same general operations on related types of
419data, but with slight variations depending on the specific type of data
420the operations are applied to.
421
995ab4ef 422=item *
ce843b44
DR
423
424It's likely you'll have to add new data types later.
425
995ab4ef 426=item *
ce843b44
DR
427
428The typical interactions between pieces of data are best represented by
429operators.
430
995ab4ef 431=item *
ce843b44
DR
432
433The implementation of individual components of the system is likely to
434change over time.
435
995ab4ef 436=item *
ce843b44
DR
437
438The system design is already object-oriented.
439
995ab4ef 440=item *
ce843b44
DR
441
442Large numbers of other programmers will be using your code modules.
443
444=back
445
dbfe2941
DR
446=head1 PERL OO SYSTEMS
447
448As we mentioned before, Perl's built-in OO system is very minimal, but
449also quite flexible. Over the years, many people have developed systems
450which build on top of Perl's built-in system to provide more features
451and convenience.
452
453We strongly recommend that you use one of these systems. Even the most
454minimal of them eliminates a lot of repetitive boilerplate. There's
455really no good reason to write your classes from scratch in Perl.
456
457If you are interested in the guts underlying these systems, check out
458L<perlobj>.
459
460=head2 Moose
461
462L<Moose> bills itself as a "postmodern object system for Perl 5". Don't
463be scared, the "postmodern" label is a callback to Larry's description
464of Perl as "the first postmodern computer language".
465
466C<Moose> provides a complete, modern OO system. Its biggest influence
467is the Common Lisp Object System, but it also borrows ideas from
468Smalltalk and several other languages. C<Moose> was created by Stevan
469Little, and draws heavily from his work on the Perl 6 OO design.
470
37fc2a72
DR
471Here is our C<File> class using C<Moose>:
472
37fc2a72
DR
473 package File;
474 use Moose;
475
476 has path => ( is => 'ro' );
477 has content => ( is => 'ro' );
478 has last_mod_time => ( is => 'ro' );
479
480 sub print_info {
481 my $self = shift;
482
483 print "This file is at ", $self->path, "\n";
484 }
485
dbfe2941
DR
486C<Moose> provides a number of features:
487
488=over 4
489
490=item * Declarative sugar
491
492C<Moose> provides a layer of declarative "sugar" for defining classes.
493That sugar is just a set of exported functions that make declaring how
494your class works simpler and more palatable. This lets you describe
495I<what> your class is, rather than having to tell Perl I<how> to
496implement your class.
497
dbfe2941
DR
498The C<has()> subroutine declares an attribute, and C<Moose>
499automatically creates accessors for these attributes. It also takes
500care of creating a C<new()> method for you. This constructor knows
501about the attributes you declared, so you can set them when creating a
37fc2a72 502new C<File>.
dbfe2941
DR
503
504=item * Roles built-in
505
506C<Moose> lets you define roles the same way you define classes:
507
31f7d6b9 508 package HasOnOffSwitch;
dbfe2941
DR
509 use Moose::Role;
510
511 has is_on => (
512 is => 'rw',
513 isa => 'Bool',
514 );
515
516 sub turn_on {
517 my $self = shift;
518 $self->is_on(1);
519 }
520
521 sub turn_off {
522 my $self = shift;
523 $self->is_on(0);
524 }
525
526=item * A miniature type system
527
528In the example above, you can see that we passed C<< isa => 'Bool' >>
529to C<has()> when creating our C<is_on> attribute. This tells C<Moose>
530that this attribute must be a boolean value. If we try to set it to an
531invalid value, our code will throw an error.
532
533=item * Full introspection and manipulation
534
535Perl's built-in introspection features are fairly minimal. C<Moose>
536builds on top of them and creates a full introspection layer for your
37fc2a72 537classes. This lets you ask questions like "what methods does the File
dbfe2941
DR
538class implement?" It also lets you modify your classes
539programmatically.
540
541=item * Self-hosted and extensible
542
543C<Moose> describes itself using its own introspection API. Besides
544being a cool trick, this means that you can extend C<Moose> using
545C<Moose> itself.
546
547=item * Rich ecosystem
548
549There is a rich ecosystem of C<Moose> extensions on CPAN under the
71c89d21 550L<MooseX|https://search.cpan.org/search?query=MooseX&mode=dist>
dbfe2941
DR
551namespace. In addition, many modules on CPAN already use C<Moose>,
552providing you with lots of examples to learn from.
553
554=item * Many more features
555
556C<Moose> is a very powerful tool, and we can't cover all of its
557features here. We encourage you to learn more by reading the C<Moose>
558documentation, starting with
71c89d21 559L<Moose::Manual|https://search.cpan.org/perldoc?Moose::Manual>.
dbfe2941
DR
560
561=back
562
563Of course, C<Moose> isn't perfect.
564
565C<Moose> can make your code slower to load. C<Moose> itself is not
566small, and it does a I<lot> of code generation when you define your
567class. This code generation means that your runtime code is as fast as
568it can be, but you pay for this when your modules are first loaded.
569
570This load time hit can be a problem when startup speed is important,
571such as with a command-line script or a "plain vanilla" CGI script that
572must be loaded each time it is executed.
573
574Before you panic, know that many people do use C<Moose> for
575command-line tools and other startup-sensitive code. We encourage you
576to try C<Moose> out first before worrying about startup speed.
577
578C<Moose> also has several dependencies on other modules. Most of these
579are small stand-alone modules, a number of which have been spun off
580from C<Moose>. C<Moose> itself, and some of its dependencies, require a
581compiler. If you need to install your software on a system without a
582compiler, or if having I<any> dependencies is a problem, then C<Moose>
583may not be right for you.
584
b20e3267 585=head3 Moo
dbfe2941
DR
586
587If you try C<Moose> and find that one of these issues is preventing you
27ffaccd
DR
588from using C<Moose>, we encourage you to consider L<Moo> next. C<Moo>
589implements a subset of C<Moose>'s functionality in a simpler package.
590For most features that it does implement, the end-user API is
b20e3267 591I<identical> to C<Moose>, meaning you can switch from C<Moo> to
dbfe2941
DR
592C<Moose> quite easily.
593
27ffaccd
DR
594C<Moo> does not implement most of C<Moose>'s introspection API, so it's
595often faster when loading your modules. Additionally, none of its
596dependencies require XS, so it can be installed on machines without a
597compiler.
dbfe2941 598
a733b0cc
DR
599One of C<Moo>'s most compelling features is its interoperability with
600C<Moose>. When someone tries to use C<Moose>'s introspection API on a
601C<Moo> class or role, it is transparently inflated into a C<Moose>
602class or role. This makes it easier to incorporate C<Moo>-using code
603into a C<Moose> code base and vice versa.
604
605For example, a C<Moose> class can subclass a C<Moo> class using
606C<extends> or consume a C<Moo> role using C<with>.
607
b20e3267 608The C<Moose> authors hope that one day C<Moo> can be made obsolete by
dbfe2941
DR
609improving C<Moose> enough, but for now it provides a worthwhile
610alternative to C<Moose>.
611
612=head2 Class::Accessor
613
614L<Class::Accessor> is the polar opposite of C<Moose>. It provides very
615few features, nor is it self-hosting.
616
617It is, however, very simple, pure Perl, and it has no non-core
618dependencies. It also provides a "Moose-like" API on demand for the
619features it supports.
620
621Even though it doesn't do much, it is still preferable to writing your
622own classes from scratch.
623
37fc2a72 624Here's our C<File> class with C<Class::Accessor>:
dbfe2941 625
37fc2a72 626 package File;
dbfe2941
DR
627 use Class::Accessor 'antlers';
628
37fc2a72
DR
629 has path => ( is => 'ro' );
630 has content => ( is => 'ro' );
631 has last_mod_time => ( is => 'ro' );
dbfe2941 632
37fc2a72 633 sub print_info {
dbfe2941
DR
634 my $self = shift;
635
37fc2a72 636 print "This file is at ", $self->path, "\n";
dbfe2941
DR
637 }
638
639The C<antlers> import flag tells C<Class::Accessor> that you want to
640define your attributes using C<Moose>-like syntax. The only parameter
641that you can pass to C<has> is C<is>. We recommend that you use this
642Moose-like syntax if you choose C<Class::Accessor> since it means you
643will have a smoother upgrade path if you later decide to move to
644C<Moose>.
645
646Like C<Moose>, C<Class::Accessor> generates accessor methods and a
647constructor for your class.
648
153621ca 649=head2 Class::Tiny
dbfe2941 650
153621ca 651Finally, we have L<Class::Tiny>. This module truly lives up to its
dbfe2941 652name. It has an incredibly minimal API and absolutely no dependencies
10e32c8d
DR
653on any recent Perl. Still, we think it's a lot easier to use than
654writing your own OO code from scratch.
dbfe2941 655
37fc2a72 656Here's our C<File> class once more:
dbfe2941 657
37fc2a72 658 package File;
153621ca 659 use Class::Tiny qw( path content last_mod_time );
dbfe2941 660
37fc2a72 661 sub print_info {
dbfe2941
DR
662 my $self = shift;
663
37fc2a72 664 print "This file is at ", $self->path, "\n";
dbfe2941
DR
665 }
666
667That's it!
668
153621ca 669With C<Class::Tiny>, all accessors are read-write. It generates a
dbfe2941
DR
670constructor for you, as well as the accessors you define.
671
153621ca
DG
672You can also use L<Class::Tiny::Antlers> for C<Moose>-like syntax.
673
dbfe2941
DR
674=head2 Role::Tiny
675
676As we mentioned before, roles provide an alternative to inheritance,
677but Perl does not have any built-in role support. If you choose to use
678Moose, it comes with a full-fledged role implementation. However, if
679you use one of our other recommended OO modules, you can still use
680roles with L<Role::Tiny>
681
682C<Role::Tiny> provides some of the same features as Moose's role
683system, but in a much smaller package. Most notably, it doesn't support
684any sort of attribute declaration, so you have to do that by hand.
685Still, it's useful, and works well with C<Class::Accessor> and
153621ca 686C<Class::Tiny>
dbfe2941
DR
687
688=head2 OO System Summary
689
690Here's a brief recap of the options we covered:
691
692=over 4
693
694=item * L<Moose>
695
696C<Moose> is the maximal option. It has a lot of features, a big
b20e3267
DR
697ecosystem, and a thriving user base. We also covered L<Moo> briefly.
698C<Moo> is C<Moose> lite, and a reasonable alternative when Moose
dbfe2941
DR
699doesn't work for your application.
700
701=item * L<Class::Accessor>
702
703C<Class::Accessor> does a lot less than C<Moose>, and is a nice
704alternative if you find C<Moose> overwhelming. It's been around a long
705time and is well battle-tested. It also has a minimal C<Moose>
706compatibility mode which makes moving from C<Class::Accessor> to
707C<Moose> easy.
708
153621ca 709=item * L<Class::Tiny>
dbfe2941 710
153621ca 711C<Class::Tiny> is the absolute minimal option. It has no dependencies,
dbfe2941
DR
712and almost no syntax to learn. It's a good option for a super minimal
713environment and for throwing something together quickly without having
714to worry about details.
715
716=item * L<Role::Tiny>
717
10e32c8d
DR
718Use C<Role::Tiny> with C<Class::Accessor> or C<Class::Tiny> if you find
719yourself considering multiple inheritance. If you go with C<Moose>, it
720comes with its own role implementation.
dbfe2941
DR
721
722=back
723
724=head2 Other OO Systems
725
726There are literally dozens of other OO-related modules on CPAN besides
727those covered here, and you're likely to run across one or more of them
728if you work with other people's code.
729
730In addition, plenty of code in the wild does all of its OO "by hand",
731using just the Perl built-in OO features. If you need to maintain such
732code, you should read L<perlobj> to understand exactly how Perl's
733built-in OO works.
734
735=head1 CONCLUSION
736
4017f822
DR
737As we said before, Perl's minimal OO system has led to a profusion of
738OO systems on CPAN. While you can still drop down to the bare metal and
966af81c
DR
739write your classes by hand, there's really no reason to do that with
740modern Perl.
dbfe2941 741
153621ca 742For small systems, L<Class::Tiny> and L<Class::Accessor> both provide
dbfe2941
DR
743minimal object systems that take care of basic boilerplate for you.
744
745For bigger projects, L<Moose> provides a rich set of features that will
10e32c8d
DR
746let you focus on implementing your business logic. L<Moo> provides a
747nice alternative to L<Moose> when you want a lot of features but need
748faster compile time or to avoid XS.
dbfe2941 749
10e32c8d 750We encourage you to play with and evaluate L<Moose>, L<Moo>,
153621ca 751L<Class::Accessor>, and L<Class::Tiny> to see which OO system is right
dbfe2941
DR
752for you.
753
754=cut