1 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML+RDFa 1.0//EN" "http://www.w3.org/MarkUp/DTD/xhtml-rdfa-1.dtd">
3 <html xmlns="http://www.w3.org/1999/xhtml">
6 <title>Introduction to Moose</title>
7 <meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
9 <meta name="generator" content="S5" />
10 <meta name="version" content="S5 1.2a2" />
11 <meta name="author" content="Eric A. Meyer" />
12 <meta name="company" content="Complex Spiral Consulting" />
13 <!-- configuration parameters -->
14 <meta name="defaultView" content="slideshow" />
15 <meta name="controlVis" content="hidden" />
16 <!-- style sheet links -->
17 <link rel="stylesheet" href="ui/default/slides.css" type="text/css" media="projection" id="slideProj" />
18 <link rel="stylesheet" href="ui/default/outline.css" type="text/css" media="screen" id="outlineStyle" />
19 <link rel="stylesheet" href="ui/default/print.css" type="text/css" media="print" id="slidePrint" />
20 <link rel="stylesheet" href="ui/default/opera.css" type="text/css" media="projection" id="operaFix" />
21 <!-- embedded styles -->
22 <style type="text/css" media="all">
23 .imgcon {width: 525px; margin: 0 auto; padding: 0; text-align: center;}
24 #anim {width: 270px; height: 320px; position: relative; margin-top: 0.5em;}
25 #anim img {position: absolute; top: 42px; left: 24px;}
26 img#me01 {top: 0; left: 0;}
27 img#me02 {left: 23px;}
29 img#me05 {top: 43px;left: 36px;}
32 <script src="ui/default/slides.js" type="text/javascript"></script>
33 <link rel="stylesheet" href="ui/custom.css" type="text/css" />
38 <div id="controls"><!-- DO NOT EDIT --></div>
39 <div id="currentSlide"><!-- DO NOT EDIT --></div>
40 <div id="header"></div>
43 <a rel="license" href="http://creativecommons.org/licenses/by-sa/3.0/us/"><img alt="Creative Commons License" style="border-width:0" src="ui/creative-commons.png" /></a>
44 <br /><span xmlns:dc="http://purl.org/dc/elements/1.1/" href="http://purl.org/dc/dcmitype/Text" property="dc:title" rel="dc:type">Introduction to Moose</span> by <span xmlns:cc="http://creativecommons.org/ns#" property="cc:attributionName">David Rolsky</span> is licensed under a <a rel="license" href="http://creativecommons.org/licenses/by-sa/3.0/us/">Creative Commons Attribution-Share Alike 3.0 United States License</a>.
47 <h2>Introduction to Moose</h2>
51 <div class="presentation">
54 <h1>Introduction to Moose</h1>
59 <h1>Introduce Yourselves</h1>
63 <li>What you do with Perl</li>
64 <li>Why you're here today (optional)</li>
69 <h1>Moose Summed Up</h1>
72 <li><strong>Declarative</strong> OO sugar</li>
73 <li>Introspectable</li>
74 <li>Extensible (MooseX::* on CPAN)</li>
79 <h1>Moose Background</h1>
82 <li>Created by Stevan Little, first released in 2006</li>
83 <li>Moose builds on Perl 5's native OO</li>
84 <li>Borrows ideas from other languages, notably Perl 6</li>
85 <li>Provides semantics for common operations</li>
89 <div class="slide fake-slide0">
90 <h1>Part 0: Moose Concepts</h1>
102 <li>Superclasses</li>
103 <li>Method modifiers</li>
104 <li>Constructor and destructor</li>
105 <li>One metaclass object</li>
108 <li>Classes do roles</li>
113 <h1>Class Example</h1>
115 <pre><code>package Person;
116 <span class="highlight">use Moose;</span></code></pre>
119 <li>Poof, a Moose-based class!</li>
127 <li>Aka property, slot, field, member variable</li>
128 <li>A piece of data owned by an object</li>
139 <li>Mutability (read-only vs read-write)</li>
140 <li>An optional type</li>
141 <li>Accessor methods</li>
142 <li>Delegation methods</li>
143 <li>Optional default value</li>
144 <li>Many more features</li>
147 <li>Stored in the object, but don't worry about that</li>
152 <h1>Attribute Example</h1>
154 <pre><code>package Person;
157 <span class="highlight">has first_name => ( is => 'rw' );</span></code></pre>
165 <li>Nothing fancy here, just Perl subroutines</li>
168 <pre><code>package Person;
171 <span class="highlight">sub greet { ... }</span></code></pre>
178 <li>Classes <strong>do</strong> (or consume) roles</li>
179 <li>Similar to mixins and Java interfaces</li>
187 <li>Like classes, can have attributes, methods, do roles</li>
188 <li>Roles can require methods</li>
189 <li>Roles are composed (flattened) into classes</li>
194 <h1>Role Example</h1>
196 <pre><code>package HasPermissions;
197 <span class="highlight">use Moose::Role;</span>
199 has is_admin => ( is => 'rw' );</code></pre>
203 <h1>Role Example</h1>
209 <pre><code>package Person;
212 <span class="highlight">with 'HasPermissions';</span></code></pre>
216 <h1>Method Modifiers</h1>
220 <li>"<strong>Before</strong> foo(), do this first"</li>
221 <li>"Do this <strong>after</strong> foo()"</li>
222 <li>"Put this code <strong>around</strong> foo()"</li>
227 <h1>Before and After</h1>
229 <pre><code>before 'foo'
230 => sub { warn 'About to call foo()' };
233 => sub { warn 'Leaving foo()' };</code></pre>
240 <pre><code>around 'foo' => sub {
241 my $real_foo = shift;
244 warn 'Just before foo()';
246 $self->$real_foo( @_, bar => 42 );
250 'modify return values'
256 <h1>Type Constraints</h1>
259 <li>NOT A FULL-BLOWN TYPE SYSTEM!</li>
260 <li>But still darn useful</li>
261 <li>Constrain attribute values</li>
262 <li>Coerce from other types</li>
267 <h1>Type Constraint Example</h1>
269 <pre><code>package Person;
274 <span class="highlight">isa => 'Int'</span>,
278 Person->new( weight => 'heavy' );</code></pre>
285 <li>Attributes can define delegations</li>
286 <li>Lets you hide some implementation details</li>
287 <li>Fewer objects to chase around</li>
294 <pre><code>package Person;
300 <span class="highlight">handles => { 'blog_host' => 'host' },</span>
303 <span class="highlight">$person->blog_host;</span>
304 # really calls $person->blog_uri->host</code></pre>
308 <h1>Constructors</h1>
311 <li>Moose creates <code>new()</code> for you</li>
312 <li>Provide an optional <code>BUILDARGS()</code> and <code>BUILD()</code></li>
320 <li>Provide an optional <code>DEMOLISH()</code></li>
325 <h1>Moose Meta-API</h1>
328 <li>Answers questions like ...
330 <li>What methods does this class have?</li>
331 <li>What are its parents?</li>
332 <li>What attributes does it have (including inherited attributes)?</li>
333 <li>What roles does it do?</li>
334 <li>Much, much, more</li>
341 <h1>Moose Meta-API</h1>
344 <li>Not just for introspection ...
346 <li>Add methods, attributes, roles, etc</li>
347 <li>Extend and alter core features</li>
357 <li>A quick bit of propaganda ...</li>
364 <pre><code>package Person;
367 has last_name => (
374 <h1>Without Moose</h1>
376 <pre class="small"><code>package Person;
386 if (exists $args{last_name}) {
387 confess "Attribute (last_name) does not pass the type constraint because: "
388 . "Validation failed for 'Str' with value $args{last_name}"
389 if ref($args{last_name});
390 $self->{last_nane} = $args{last_name};
393 return bless $self, $class;
401 confess "Attribute (last_name) does not pass the type constraint because: "
402 . "Validation failed for 'Str' with value $value"
404 $self->{last_name} = $value;
407 return $self->{last_name};
413 <h1>Side by side</h1>
415 <table class="side-by-side">
418 <pre><code>package Person;
421 has last_name => (
427 <pre class="small"><code>package Person;
437 if (exists $args{last_name}) {
438 confess "Attribute (last_name) does not pass the type constraint because: "
439 . "Validation failed for 'Str' with value $args{last_name}"
440 if ref($args{last_name});
441 $self->{last_nane} = $args{last_name};
444 return bless $self, $class;
452 confess "Attribute (last_name) does not pass the type constraint because: "
453 . "Validation failed for 'Str' with value $value"
455 $self->{last_name} = $value;
458 return $self->{last_name};
467 <h1>Side by side</h1>
469 <table class="side-by-side">
472 <pre><code><span class="match-moose">package Person;</span>
475 has last_name => (
481 <pre class="small"><code><span class="match-unsweet">package Person;</span>
491 if (exists $args{last_name}) {
492 confess "Attribute (last_name) does not pass the type constraint because: "
493 . "Validation failed for 'Str' with value $args{last_name}"
494 if ref($args{last_name});
495 $self->{last_nane} = $args{last_name};
498 return bless $self, $class;
506 confess "Attribute (last_name) does not pass the type constraint because: "
507 . "Validation failed for 'Str' with value $value"
509 $self->{last_name} = $value;
512 return $self->{last_name};
520 <h1>Side by side</h1>
522 <table class="side-by-side">
525 <pre><code>package Person;
526 <span class="match-moose">use Moose;</span>
528 has last_name => (
534 <pre class="small"><code>package Person;
535 <span class="match-unsweet">use strict;
542 my $self = {};</span>
544 if (exists $args{last_name}) {
545 confess "Attribute (last_name) does not pass the type constraint because: "
546 . "Validation failed for 'Str' with value $args{last_name}"
547 if ref($args{last_name});
548 $self->{last_nane} = $args{last_name};
551 <span class="match-unsweet">return bless $self, $class;
559 confess "Attribute (last_name) does not pass the type constraint because: "
560 . "Validation failed for 'Str' with value $value"
562 $self->{last_name} = $value;
565 return $self->{last_name};
573 <h1>Side by side</h1>
575 <table class="side-by-side">
578 <pre><code>package Person;
581 <span class="match-moose">has last_name => (</span>
584 <span class="match-moose">);</span></code></pre>
587 <pre class="small"><code>package Person;
597 <span class="match-unsweet">if (exists $args{last_name}) {</span>
598 confess "Attribute (last_name) does not pass the type constraint because: "
599 . "Validation failed for 'Str' with value $args{last_name}"
600 if ref($args{last_name});
601 <span class="match-unsweet">$self->{last_nane} = $args{last_name};
604 return bless $self, $class;
612 confess "Attribute (last_name) does not pass the type constraint because: "
613 . "Validation failed for 'Str' with value $value"
615 $self->{last_name} = $value;
618 return $self->{last_name};
626 <h1>Side by side</h1>
628 <table class="side-by-side">
631 <pre><code>package Person;
634 has last_name => (
635 <span class="match-moose">is => 'rw',</span>
640 <pre class="small"><code>package Person;
650 if (exists $args{last_name}) {
651 confess "Attribute (last_name) does not pass the type constraint because: "
652 . "Validation failed for 'Str' with value $args{last_name}"
653 if ref($args{last_name});
654 $self->{last_nane} = $args{last_name};
657 return bless $self, $class;
660 <span class="match-unsweet">sub last_name {
664 my $value = shift;</span>
665 confess "Attribute (last_name) does not pass the type constraint because: "
666 . "Validation failed for 'Str' with value $value"
668 <span class="match-unsweet">$self->{last_name} = $value;
671 return $self->{last_name};
672 }</span></code></pre>
679 <h1>Side by side</h1>
681 <table class="side-by-side">
684 <pre><code>package Person;
687 has last_name => (
689 <span class="match-moose">isa => 'Str',</span>
693 <pre class="small"><code>package Person;
703 if (exists $args{last_name}) {
704 <span class="match-unsweet">confess "Attribute (last_name) does not pass the type constraint because: "
705 . "Validation failed for 'Str' with value $args{last_name}"
706 if ref($args{last_name});</span>
707 $self->{last_nane} = $args{last_name};
710 return bless $self, $class;
718 <span class="match-unsweet">confess "Attribute (last_name) does not pass the type constraint because: "
719 . "Validation failed for 'Str' with value $value"
720 if ref($value);</span>
721 $self->{last_name} = $value;
724 return $self->{last_name};
732 <h1>Side by side</h1>
734 <table class="side-by-side">
735 <tr class="incremental">
739 <tr class="incremental">
740 <td>92 characters</td>
741 <td>741 characters</td>
745 <pre><code>package Person;
748 has last_name => (
754 <pre class="small"><code>package Person;
764 if (exists $args{last_name}) {
765 confess "Attribute (last_name) does not pass the type constraint because: "
766 . "Validation failed for 'Str' with value $args{last_name}"
767 if ref($args{last_name});
768 $self->{last_nane} = $args{last_name};
771 return bless $self, $class;
779 confess "Attribute (last_name) does not pass the type constraint because: "
780 . "Validation failed for 'Str' with value $value"
782 $self->{last_name} = $value;
785 return $self->{last_name};
795 <pre class="small"><code>sub new {
800 if (exists $args{last_name}) {
801 confess "Attribute (last_name) does not pass the type constraint because: "
802 . "Validation failed for 'Str' with value $args{last_name}"
803 if ref($args{last_name});
804 $self->{last_nane} = $args{last_name};
807 return bless $self, $class;
814 <pre class="small"><code>if (exists $args{last_name}) {
815 confess "Attribute (last_name) does not pass the type constraint because: "
816 . "Validation failed for 'Str' with value $args{last_name}"
817 if ref($args{last_name});
818 $self->{last_nane} = $args{last_name};
825 <code>$self->{last_nane} = $args{last_name};</code>
830 <code>$self->{last_na<span class="wrong">n</span>e}</code>
836 <pre><code>package Person;
839 has last_name => (
846 <h1>More Why Moose?</h1>
849 <li>Less code == fewer bugs</li>
850 <li>Moose is well-tested, test your own code, not Moose</li>
851 <li>Focus on <strong>what</strong>, not <strong>how</strong></li>
855 <div class="slide fake-slide0">
856 <h1>Part 1: Moose Classes</h1>
860 <h1>Moose Classes</h1>
863 <li>Moose classes are Perl packages which <code>use Moose</code></li>
868 <h1>Moose.pm and Your Class</h1>
870 <pre><code>package Person;
871 use Moose;</code></pre>
874 <li><code>Moose.pm</code> provides declarative sugar</li>
875 <li>Turns on <code>strict</code> and <code>warnings</code></li>
876 <li>Creates metaclasses for your class: <code>Person->meta</code></li>
877 <li>Moose classes automatically inherit from <code>Moose::Object</code></li>
882 <h1>What <code>Moose::Object</code> Provides</h1>
885 <li>Constructor - <code>new()</code></li>
886 <li>Calls your <code>BUILDARGS()</code> and/or <code>BUILD()</code></li>
887 <li>Calls your <code>DEMOLISH</code> during object destruction</li>
895 <li>Takes <code>@_</code>, returns a hash reference of attribute name/value pairs</li>
896 <li>Accepts a hash or hashref; throws otherwise</li>
897 <li>Provide your own for other cases</li>
898 <li><strong>Always</strong> call <code>$class->SUPER::BUILDARGS(@_)</code> as a fallback!</li>
903 <h1>BUILDARGS Example</h1>
905 <pre><code>package Person;
911 if ( @_ == 1 && ! ref $_[0] ) {
912 <span class="highlight">return { ssn => $_[0] };</span>
914 <span class="highlight">return $class->SUPER::BUILDARGS(@_)</span>;
917 <span class="highlight">Person->new('123-45-6789')</span></code></pre>
924 <li>Called after object is created, before <code>new</code> returns</li>
925 <li>Chance to do more complex validation, set complex attributes</li>
926 <li>Called in reverse inheritance order, parents to children</li>
927 <li>Return value is ignored</li>
932 <h1>BUILD Example</h1>
934 <pre><code>package Person;
940 if ( $self->country_of_residence
942 die 'All US residents'
943 . ' must have an SSN'
944 unless $self->has_ssn;
950 <h1>Object Construction a la Moose</h1>
952 <pre><code>Person->new(@_)</code></pre>
954 <ol style="margin-top: 0">
955 <li>Calls <code>Person->BUILDARGS(@_)</code> to turn <code>@_</code> into a hashref</li>
956 <li>Blesses a reference</li>
957 <li>Populates attributes based on the hashref from #1</li>
958 <li>Calls <code>$new_object->BUILDALL($constructor_args)</code>
959 <br />... which calls all <code>BUILD</code> methods</li>
960 <li>Returns the object</li>
965 <h1>The Object is Opaque</h1>
968 <li>Technically it's a hash reference</li>
969 <li><span class="wrong">If you <em>ever</em> treat it as one <strong>you are doing it wrong!</strong></span></li>
977 <li>Like <code>DESTROY</code>, but Moose makes sure all <code>DEMOLISH</code> methods in a hierarchy are called</li>
978 <li>Called in normal inheritance order, children to parents</li>
986 <li><code>extends</code> is sugar for declaring parent classes</li>
987 <li>Also ensures metaclass compatibility between parent and child</li>
988 <li>Do not <code>use base</code></li>
991 <pre><code>package Employee;
993 <span class="highlight">extends 'Person';</span></code></pre>
1000 <li>Each call to <code>extends</code> <strong>resets</strong> your parents</li>
1003 <h2 class="wrong">Wrong</h2>
1005 <pre><code>package EvilEmployee;
1008 extends 'Thief';</code></pre>
1010 <h2 class="right">Right</h2>
1012 <pre><code>package EvilEmployee;
1014 extends 'Person', 'Thief';</code></pre>
1018 <h1>Extending un-Moose-y Parents</h1>
1020 <pre><code>package My::LWP;
1022 extends 'LWP';</code></pre>
1025 <li>No <code>Moose::Object</code>, so ...
1027 <li>No attribute-handling <code>new()</code></li>
1028 <li>No <code>BUILDARGS()</code> or <code>BUILD()</code></li>
1029 <li>No <code>DEMOLISH()</code></li>
1032 <li>But see <code>MooseX::NonMoose</code> for a workaround</li>
1037 <h1><code>override</code> and <code>super</code></h1>
1040 <li><code>override</code> is another method modifier</li>
1041 <li>An alternative to Perl's <code>SUPER::</code></li>
1046 <h1><code>override</code> and <code>super</code></h1>
1048 <pre><code>package Employee;
1051 <span class="current incremental">extends 'Person';</span>
1053 <span class="incremental">override</span> work => sub {
1057 unless $self->got_paid;
1058 <span class="incremental">super();</span>
1059 }<span class="incremental">;</span></code></pre>
1063 <h1>Caveat <code>super</code></h1>
1066 <li>Mostly like <code>$self->SUPER::work(@_)</code></li>
1067 <li><strong>But</strong> cannot change <code>@_</code>!</li>
1068 <li>Binds the parent's method at compile time</li>
1069 <li>Parent determined by checking <code>Child->meta()->superclasses()</code></li>
1074 <h1>Minimal Attributes</h1>
1077 <li><code>has 'foo'</code></li>
1078 <li>Use <code>is => 'ro'</code> or <code>is => 'rw'</code></li>
1079 <li>Attributes without "is" have no accessors</li>
1084 <h1>Read-write attributes</h1>
1086 <pre><code>package Person;
1089 has first_name => ( <span class="highlight">is => 'rw'</span> );
1092 Person->new( first_name => 'Dave' );
1094 $person->first_name('Stevan');
1095 print $person->first_name; # Stevan</code></pre>
1100 <h1>Read-only attributes</h1>
1102 <pre><code>package Person;
1105 has first_name => ( <span class="highlight">is => 'ro'</span> );
1108 Person->new( first_name => 'Dave' );
1110 $person->first_name('Stevan');
1111 print $person->first_name; # Dave</code></pre>
1116 <h1>There is More to Come</h1>
1119 <li>Attributes have a <em>lot</em> of features</li>
1124 <h1>Cleaning Up Moose Droppings</h1>
1126 <pre><code>package Person;
1130 Person->can('extends');</code></pre>
1133 <li>Not very hygienic</li>
1138 <h1>Cleaning Up Moose Droppings</h1>
1140 <pre><code>package Person;
1145 <span class="highlight">no Moose;</span>
1148 Person->can('extends');</code></pre>
1152 <h1>Cleaning Up Moose Droppings</h1>
1154 <pre><code>package Person;
1155 <span class="highlight">use namespace::autoclean;</span>
1161 Person->can('extends');</code></pre>
1168 <li>Cleaning up is a best practice</li>
1169 <li>Say <code>no Moose</code> at the end of a package</li>
1170 <li>Or <code>use namespace::autoclean</code> at the top</li>
1176 <h1>Immutability</h1>
1179 <li><span style="font-family: URW Chancery L; font-size: 120%">Stevan's Incantation of Fleet-Footedness</span></li>
1182 <pre><code>package Person;
1185 <span class="highlight">__PACKAGE__->meta->make_immutable;</span></code></pre>
1189 <h1>What <code>make_immutable</code> does</h1>
1193 <li>Uses <code>eval</code> to "inline" a constructor</li>
1194 <li>Memoizes a lot of meta-information</li>
1195 <li>Makes loading your class slower</li>
1196 <li>Makes object creation <em>much</em> faster</li>
1201 <h1>When to Immutabilize?</h1>
1204 <li><em>Almost</em> always</li>
1205 <li>Startup time vs execution time</li>
1210 <h1>Classes Summary</h1>
1213 <li><code>use Moose</code></li>
1214 <li><code>Class->meta</code></li>
1215 <li><code>Moose::Object</code> base class</li>
1216 <li><code>extends</code>, <code>override</code>, and <code>super</code></li>
1217 <li>Simple attributes: <code>has</code>, <code>is => 'ro'</code>, & <code>is => 'rw'</code></li>
1218 <li><code>no Moose</code></li>
1219 <li><code>__PACKAGE__->meta->make_immutable</code></li>
1232 # perl bin/prove -lv t/00-prereq.t
1234 # perl install-moose (if needed)
1236 # perl bin/prove -lv t/01-classes.t
1238 # edit lib/Person.pm and lib/Employee.pm
1240 Iterate til this passes all its tests</pre>
1243 <div class="slide fake-slide0">
1244 <h1>Part 2: Roles</h1>
1248 <h1>Just What Is a Role?</h1>
1251 <li>Mixin? Interface? Trait?</li>
1252 <li>Yes ... and more!</li>
1257 <h1>Roles - State <strong>and</strong> Behavior</h1>
1259 <pre><code>package HasPermissions;
1261 <span class="current incremental"># state
1262 has access_level => ( is => 'rw' );</span>
1264 <span class="incremental"># behavior
1267 my $required = shift;
1269 return $self->access_level
1271 }</span></code></pre>
1276 <h1>Roles Can Define Interfaces</h1>
1278 <pre><code>package Printable;
1281 requires 'as_string';</code></pre>
1285 <h1>Roles Can Do All Three</h1>
1287 <pre><code>package Printable;
1290 requires 'as_string';
1292 has has_been_printed => ( is => 'rw' );
1296 print $self->as_string;
1297 $self->has_been_printed(1);
1302 <h1>Classes Consume Roles</h1>
1304 <pre><code>package Person;
1307 with 'HasPermissions';</code></pre>
1311 <h1>Classes Consume Roles</h1>
1313 <pre><code>my $person = Person->new(
1314 first_name => 'Kenichi',
1315 last_name => 'Asai',
1316 access_level => 42,
1319 print $person->full_name
1321 . $person->can_access(42)
1323 : 'little power';</code></pre>
1327 <h1>Roles in Practice</h1>
1330 <li>Consuming a role =~ inlining the role</li>
1335 <h1>In Other Words ...</h1>
1337 <pre><code>package Person;
1340 <span class="highlight">with 'Printable';</span></code></pre>
1344 <h1>In Other Words ...</h1>
1346 <pre><code>package Person;
1349 <span class="delete">with 'Printable';</span>
1351 <span class="highlight">die '...' unless __PACKAGE__->can('as_string');
1353 has has_been_printed => ( is => 'rw' );
1357 print $self->as_string;
1358 $self->has_been_printed(1);
1359 }</span></code></pre>
1366 <li>Role consumption is introspectable</li>
1369 <pre><code>if ( Person->does('Printable') ) { ... }
1373 Person->meta->does('Printable')</code></pre>
1378 <h1>These Names Are the Same</h1>
1381 <li>What if a role and class define the same method?</li>
1382 <li>A class's <em>local</em> methods win over the role's</li>
1383 <li>The role's methods win over the class's <em>inherited</em> methods</li>
1388 <h1>Conflicts Between Roles</h1>
1391 <li>Two roles with a method of the same name</li>
1392 <li>Generates a compile-time error when consumed by a class</li>
1397 <h1>Conflict Example</h1>
1399 <pre><code>package IsFragile;
1404 package CanBreakdance;
1407 sub break { ... }</code></pre>
1411 <h1>Conflict Example</h1>
1413 <pre><code>package FragileDancer;
1416 <span class="highlight">with 'IsFragile', 'CanBreakdance';</span></code></pre>
1419 <li>Only one <code>with</code>!</li>
1424 <h1>Conflict Resolution</h1>
1427 <li>The consuming class must resolve the conflict by implementing the method</li>
1428 <li>Can use some combination of method exclusion and aliasing</li>
1433 <h1>Method Aliasing</h1>
1435 <pre><code>package FragileDancer;
1438 <span class="highlight">with 'IsFragile' =>
1440 { break => 'break_bone' } },
1443 { break => 'break_it_down' } };</span></code></pre>
1446 <li>Renames the roles' methods</li>
1447 <li>Still conflicts, need to <code>exclude</code> as well</li>
1452 <h1>Method Exclusion</h1>
1454 <pre><code>package FragileDancer;
1457 <span class="highlight">with 'IsFragile' =>
1459 { break => 'break_bone' },
1460 -excludes => 'break' },
1463 { break => 'break_it_down' },
1464 -excludes => 'break' };</span></code></pre>
1468 <h1>And then ...</h1>
1470 <pre><code>package FragileDancer;
1476 $self->break_it_down;
1477 if ( rand(1) < 0.5 ) {
1478 $self->break_bone;
1484 <h1>Still Full of Fail</h1>
1487 <li>Roles are also about semantics!</li>
1488 <li>We've fulfilled the letter and lost the spirit</li>
1489 <li>Roles have a <em>meaning</em></li>
1490 <li>Think twice before blindly aliasing and excluding methods!</li>
1495 <h1>Hot Role-on-Role Action</h1>
1497 <pre><code>package Comparable;
1500 requires 'compare';</code></pre>
1504 <h1>Hot Role-on-Role Action</h1>
1506 <pre><code>package TestsEquality;
1513 return $self->compare(@_) == 0;
1518 <h1>And then ...</h1>
1520 <pre><code>package Integer;
1523 with 'TestsEquality';
1525 # Satisfies the Comparable role
1528 Integer->does('TestsEquality'); # true
1529 Integer->does('Comparable'); # also true!</code></pre>
1533 <h1>Name Conflicts Between Roles</h1>
1535 <pre><code>package HasSubProcess;
1538 <span class="highlight">sub execute { ... }</span>
1543 with 'HasSubProcess';
1545 <span class="highlight">sub execute { ... }</span></code></pre>
1549 <h1>Delayed Conflict</h1>
1551 <pre><code>package StateOfTexas;
1552 with 'Killer';</code></pre>
1555 <li><code>StateOfTexas</code> must implement its own <code>execute</code></li>
1556 <li>But loading the <code>Killer</code> role by itself does not cause an error</li>
1561 <h1>Roles as Interfaces</h1>
1564 <li>Roles can <code>require</code> methods of their consumers</li>
1565 <li>Compile-time checks</li>
1566 <li>Method must exist when the role is consumed</li>
1571 <h1>The Attribute Gotcha</h1>
1573 <pre><code>package HasSize;
1576 <span class="current incremental">requires 'size';</span>
1581 <span class="incremental">with 'HasSize';
1583 has size => ( is => 'ro' );</span></code></pre>
1587 <h1>The Attribute Gotcha Workaround</h1>
1589 <pre><code>package HasSize;
1597 has size => ( is => 'ro' );
1599 with 'HasSize';</code></pre>
1603 <h1>Compile-time Is a Lie</h1>
1606 <li>Really, it's <em>package load</em> time</li>
1607 <li>That's run-time, but before the "real" run-time</li>
1608 <li>Moose does not rewire Perl, it's just sugar!</li>
1609 <li>(but <code>MooseX::Declare</code> <em>does</em> rewire Perl)</li>
1614 <h1>Enforcing Roles</h1>
1616 <pre><code>package Comparison;
1619 has [ 'left', 'right' ] => (
1621 <span class="highlight">does => 'Comparable',</span>
1626 <li>A sneak peek at type constraints</li>
1632 <h1>Roles Can Be Applied to Objects</h1>
1634 <pre><code>use Moose::Util qw( apply_all_roles );
1636 my $fragile_person = Person->new( ... );
1637 apply_all_roles( $fragile_person,
1638 'IsFragile' );</code></pre>
1641 <li>Does not change the <code>Person</code> class</li>
1642 <li>Works with non-Moose classes, great for monkey-patching!</li>
1647 <h1>Roles Are Dirty Too</h1>
1650 <li>Once again, clean up those Moose droppings</li>
1653 <pre><code>package Comparable;
1658 <span class="highlight">no Moose::Role;</span></code></pre>
1661 <li>But roles cannot be made immutable</li>
1666 <h1>The Zen of Roles</h1>
1669 <li>Roles represent discrete units of ...
1676 <li>Roles are shareable between unrelated classes</li>
1677 <li>Roles are what a class <em>does</em>, not what it <em>is</em></li>
1678 <li>Roles <em>add</em> functionality, inheritance <em>specializes</em></li>
1683 <h1>Abstract Examples</h1>
1686 <li>Human <em>@ISA</em> Animal</li>
1687 <li>Human <em>does</em> Toolmaker (as <em>does</em> Chimpanzee)</li>
1688 <li>Car <em>@ISA</em> Vehicle</li>
1689 <li>Car <em>does</em> HasEngine</li>
1694 <h1>Real Examples</h1>
1697 <li>Objects representing SQL database components and queries
1699 <li>Schema, Table, Column, ColumnAlias</li>
1700 <li>Select, Insert, Update, Delete</li>
1707 <h1>Real Examples</h1>
1710 <li>Column and ColumnAlias both <em>do</em> ColumnLike</li>
1711 <li>ColumnLike things can be used in certain parts of queries</li>
1712 <li>All queries <em>do</em> HasWhereClause</li>
1713 <li>Select <em>does</em> Comparable and Selectable (for subselects)</li>
1714 <li>A where clause requires its components to <em>do</em> Comparable</li>
1719 <h1>Roles Summary</h1>
1722 <li>Roles can define an interface with <code>requires</code></li>
1723 <li>Roles can have state (attributes) and behavior (methods)</li>
1724 <li>Roles can mix interface, state, & behavior</li>
1725 <li>Roles are composed (flattened) into classes</li>
1726 <li>Roles can do other roles</li>
1727 <li>Roles can be used as a type in APIs (must do Comparable)</li>
1739 # perl bin/prove -lv t/02-roles.t
1741 Iterate til this passes all its tests</pre>
1744 <div class="slide fake-slide0">
1745 <h1>Part 3: Basic Attributes</h1>
1749 <h1>Attributes Are Huge</h1>
1752 <li>Moose's biggest feature</li>
1753 <li>The target of <em>many</em> MooseX modules</li>
1758 <h1>Quick Review</h1>
1761 <li>Declared with <code>has</code></li>
1762 <li>Read-only or read-write</li>
1765 <pre><code>package Shirt;
1768 has 'color' => ( is => 'ro' );
1769 has 'is_ripped' => ( is => 'rw' );</code></pre>
1773 <h1>Required-ness</h1>
1776 <li>Required means "must be passed to the constructor"</li>
1777 <li>But can be <code>undef</code></li>
1782 <h1>Required-ness</h1>
1784 <pre><code>package Person;
1787 has first_name => (
1789 <span class="current incremental">required => 1,</span>
1792 <span class="incremental">Person->new( first_name => undef ); # ok
1793 Person->new(); # kaboom</span></code></pre>
1797 <h1>Default and Builder</h1>
1800 <li>Attributes can have defaults</li>
1801 <li>Simple non-reference scalars (number, string)</li>
1802 <li>Subroutine reference</li>
1803 <li>A builder method</li>
1811 <li>Can be a non-reference scalar (including <code>undef</code>)</li>
1814 <pre><code>package Person;
1819 default => 'Spire FCU',
1827 <li>Can be a subroutine reference</li>
1830 <pre><code>package Person;
1837 name => 'Spire FCU' ) },
1842 <h1>Subroutine Reference Default</h1>
1845 <li>Called as a method on the object</li>
1846 <li>Called anew for each object</li>
1851 <h1>Why No Other Reference Types?</h1>
1853 <pre><code>package Person;
1858 <span class="wrong">default => Bank->new(
1859 name => 'Spire FCU' ),</span>
1863 <li>Now <strong>every</strong> person shares the <strong>same</strong> Bank object!</li>
1868 <h1>Defaulting to an Empty Reference</h1>
1870 <pre><code>package Person;
1873 has packages => (
1875 default => <span class="highlight">sub { [] }</span>,
1880 <h1>What if I Want to Share?</h1>
1882 <pre><code>package Person;
1885 my $highlander_bank =
1887 name => 'Clan MacLeod Trust' );
1891 default => sub { $highlander_bank },
1899 <li>A method <em>name</em></li>
1900 <li>When called, this method returns the default value</li>
1907 <pre><code>package Person;
1912 builder => '_build_bank',
1917 return Bank->new(
1918 name => 'Spire FCU' );
1923 <h1>Default vs Builder</h1>
1926 <li>Use default for simple scalars</li>
1927 <li>Use default to return empty references</li>
1928 <li>Use default for <em>very</em> trivial subroutine references</li>
1929 <li>Use builder for everything else</li>
1934 <h1>Builder Bonuses</h1>
1937 <li>Can be overridden and method modified, because it's called by <em>name</em></li>
1938 <li>Roles can require a builder</li>
1943 <h1>Role Requires Builder</h1>
1945 <pre><code>package HasBank;
1948 requires '_build_bank';
1952 builder => '_build_bank',
1957 <h1>Lazy, Good for Nothin' Attributes</h1>
1960 <li>Normally, defaults are generated during object construction</li>
1961 <li>This can be expensive</li>
1962 <li>We want to default to <code>$self->size * 2</code>, but attribute initialization order is unpredictable</li>
1963 <li>Use lazy attributes!</li>
1968 <h1>The Power of Dynamic Defaults</h1>
1970 <pre><code>package Person;
1973 has shoe_size => (
1975 required => 'ro',
1980 <h1>The Power of Dynamic Defaults</h1>
1982 <pre><code>has shoes => (
1984 <span class="highlight">lazy => 1,</span>
1985 builder => '_build_shoes',
1991 return Shoes->new(
1992 size => <span class="highlight">$self->shoe_size</span> );
1997 <h1>Lazy is Good</h1>
2000 <li>Lazy defaults are executed when the attribute is read</li>
2001 <li>Can see other object attributes</li>
2002 <li>Still need to watch out for circular laziness</li>
2007 <h1>Clearer and Predicate</h1>
2010 <li>Attributes can have a value, including <code>undef</code>, or not</li>
2011 <li>Can clear the value with a clearer method</li>
2012 <li>Can check for the existence of a value with a predicate method</li>
2013 <li>By default, these methods are not created</li>
2018 <h1>Clearer and Predicate</h1>
2020 <pre><code>package Person;
2026 builder => '_build_account',
2027 <span class="highlight">clearer => '_clear_account',
2028 predicate => 'has_account',</span>
2033 <h1>Clearer and Lazy Defaults</h1>
2036 <li>Lazy defaults are good for computed attributes</li>
2037 <li>Clear the attribute when the source data changes</li>
2038 <li>Recalculated at next access</li>
2043 <h1>Renaming constructor arguments</h1>
2046 <li>By default, constructor names = attribute names</li>
2047 <li>Use <code>init_arg</code> to change this</li>
2048 <li>Set <code>init_arg => undef</code> to make it unconstructable</li>
2053 <h1>Some <code>init_arg</code> examples</h1>
2055 <pre><code>package Person;
2060 <span class="highlight">init_arg => 'foot_size',</span>
2063 Person->new( <span class="wrong">shoe_size => 13</span> );
2066 Person->new( <span class="right">foot_size => 13</span> );
2067 print $person->shoe_size;</code></pre>
2071 <h1>Some <code>init_arg</code> examples</h1>
2073 <pre><code>package Person;
2078 <span class="highlight">init_arg => undef,</span>
2081 Person->new( <span class="wrong">shoes => Shoes->new</span> );</code></pre>
2085 <h1>Why Set <code>init_arg => undef</code>?</h1>
2088 <li>Use this with a lazy default for attributes-as-cache</li>
2089 <li>Compute the value as needed</li>
2090 <li>Ensure that it is always generated correctly (not set by constructor)</li>
2091 <li>Use triggers or method modifiers (coming soon) to clear the value</li>
2096 <h1>Attribute Inheritance</h1>
2099 <li>By default, subclasses inherit attribute as-is</li>
2100 <li>Can change some attribute parameters in subclasses
2106 <li>others we've not yet covered</li>
2113 <h1>Attribute Inheritance Example</h1>
2115 <pre><code>package Employee;
2120 has '<span class="highlight">+first_name</span>' => (
2121 default => 'Joe',
2126 <h1>Attribute Inheritance Warning</h1>
2129 <li>An attribute is a contract about a class's API</li>
2130 <li>Don't break that contract in a subclass</li>
2131 <li>Especially important in the context of types</li>
2136 <h1>Changing Accessor Names</h1>
2138 <pre><code>package Person;
2141 has first_name => (
2142 <span class="highlight">accessor</span> => 'first_name',
2146 <li>The long-hand version of <code>is => 'rw'</code></li>
2151 <h1>Changing Accessor Names</h1>
2153 <pre><code>package Person;
2156 has first_name => (
2157 <span class="highlight">reader</span> => 'first_name',
2158 <span class="highlight">writer</span> => undef,
2162 <li>The long-hand version of <code>is => 'ro'</code></li>
2168 <h1>Changing Accessor Names</h1>
2170 <pre><code>package Person;
2173 has first_name => (
2174 <span class="highlight">reader</span> => 'get_first_name',
2175 <span class="highlight">writer</span> => 'set_first_name',
2180 <h1>Changing Accessor Names</h1>
2182 <pre><code>package Person;
2185 has first_name => (
2186 <span class="highlight">is</span> => 'rw',
2187 <span class="highlight">writer</span> => '_first_name',
2191 <li>Can also mix-and-match <code>is</code> and explicit names</li>
2196 <h1>ETOOMUCHTYPING</h1>
2199 <li><code>MooseX::FollowPBP</code><br /><code>get_foo</code> and <code>set_foo</code></li>
2200 <li><code>MooseX::SemiAffordanceAccessor</code><br /><code>foo</code> and <code>set_foo</code></li>
2205 <h1>ETOOMUCHTYPING</h1>
2207 <pre><code>package Person;
2209 <span class="highlight">use MooseX::SemiAffordanceAccessor;</span>
2211 has first_name => (
2216 <li>Creates <code>first_name</code> and <code>set_first_name</code></li>
2221 <h1>Basic Attributes Summary</h1>
2224 <li>Attributes can be <code>required</code></li>
2225 <li>Attributes can have a <code>default</code> or <code>builder</code></li>
2226 <li>Attributes with a default or builder can be <code>lazy</code></li>
2227 <li>Attributes can have a <code>clearer</code> and/or <code>predicate</code></li>
2232 <h1>Basic Attributes Summary</h1>
2235 <li>An attribute's constructor name can be changed with <code>init_arg</code></li>
2236 <li>A subclass can alter its parents' attributes</li>
2237 <li>Attribute accessor names can be changed</li>
2249 # perl bin/prove -lv \
2250 t/03-basic-attributes.t
2252 Iterate til this passes all its tests</pre>
2255 <div class="slide fake-slide0">
2256 <h1>Part 4: Method Modifiers</h1>
2260 <h1>What is a Method Modifier</h1>
2263 <li>Apply to an existing method</li>
2264 <li>... that comes from a parent class, the current class, or a role</li>
2265 <li>Roles can provide modifiers that are applied at composition time</li>
2270 <h1>What Are Method Modifiers For?</h1>
2273 <li>"Inject" behavior</li>
2274 <li>Add behavior to generated methods (accessors, delegations)</li>
2275 <li>Added from a role, can modify existing behavior</li>
2280 <h1>Before and After</h1>
2283 <li>Simplest modifiers - <code>before</code> and <code>after</code></li>
2284 <li>Guess when they run!</li>
2289 <h1>Uses for <code>before</code></h1>
2292 <li>As a pre-call check</li>
2295 <pre><code>package Person;
2298 before work => sub {
2300 die 'I have no job!'
2301 unless $self->has_title;
2306 <h1>Uses for <code>before</code></h1>
2309 <li>Logging/Debugging</li>
2312 <pre><code>package Person;
2315 before work => sub {
2317 return unless $DEBUG;
2319 warn "Called work on ",
2320 $self->full_name,
2321 "with the arguments: [@_]\n";
2326 <h1>Uses for <code>after</code></h1>
2329 <li>Also works for logging/debugging</li>
2330 <li>Post-X side-effects (recording audit info)</li>
2333 <pre><code>package Person;
2336 after work => sub {
2338 $self->work_count(
2339 $self->work_count + 1 );
2347 <li>Modifiers are useful for adding behavior to generated methods</li>
2352 <h1>More Modifier Examples</h1>
2354 <pre><code>has password => (
2356 clearer => 'clear_password',
2358 has hashed_password => (
2360 builder => '_build_hashed_password',
2361 clearer => '_clear_hashed_password',
2363 after clear_password => sub {
2365 $self->_clear_hashed_password;
2370 <h1><code>before</code> and <code>after</code> Limitations</h1>
2373 <li>Cannot alter method parameters</li>
2374 <li>Cannot alter return value</li>
2375 <li>But <strong>can</strong> throw an exception</li>
2380 <h1>The <code>around</code> Modifier</h1>
2383 <li>The big gun</li>
2384 <li>Can alter parameters <strong>and/or</strong> return values</li>
2385 <li>Can skip calling the wrapped method entirely</li>
2390 <h1>The power of <code>around</code></h1>
2392 <pre><code>around insert => sub {
2396 $self->_validate_insert(@_);
2400 $self->_munge_insert(@_) );
2402 $new_user->_assign_uri;
2408 <h1>Modifier Order</h1>
2411 <li>Before runs in order from last to first</li>
2412 <li>After runs in order from first to last</li>
2413 <li>Around runs in order from last to first</li>
2418 <h1>Modifier Order Illustrated</h1>
2421 <span class="current incremental">before 2
2423 <span class="incremental">around 2
2425 <span class="incremental">wrapped method</span>
2426 <span class="incremental">around 1
2428 <span class="incremental">after 1
2434 <h1>Modifiers in Roles</h1>
2437 <li>Roles can use these modifiers</li>
2438 <li>Very powerful!</li>
2443 <h1>Modifiers in Roles</h1>
2445 <pre><code>package IsUnreliable;
2448 <span class="highlight">requires 'run';
2450 around run</span> => sub {
2454 return if rand(1) < 0.5;
2456 return $self->$orig(@_);
2461 <h1>Augment and Inner</h1>
2464 <li>Inverted <code>super</code></li>
2465 <li>From least- to most-specific</li>
2466 <li>Like Mason's autohandler feature</li>
2467 <li>Grandparent to parent to child</li>
2468 <li>Not allowed in roles</li>
2473 <h1>Augment and Inner</h1>
2475 <pre><code>package Document;
2477 sub xml { '<doc>' . <span class="highlight">inner()</span> . '</doc>' }
2481 <span class="highlight">augment xml</span> =>
2482 sub { title() . <span class="highlight">inner()</span> . summary() };
2486 <span class="highlight">augment xml</span> =>
2487 sub { tps_xml() . <span class="highlight">inner()</span> };</code></pre>
2491 <h1>Augment and Inner</h1>
2494 <li>When we call <code>$tps->xml</code> ...
2496 <li><code>Document->xml</code></li>
2497 <li><code>Report->xml</code></li>
2498 <li><code>TPSReport->xml</code></li>
2505 <h1>Augment and Inner Usage</h1>
2508 <li>Call <code>inner()</code> to "fill in the blank"</li>
2509 <li>Requires designing for subclassing</li>
2510 <li>Call <code>inner()</code> in the terminal class, just in case</li>
2515 <h1>Method Modifiers Summary</h1>
2518 <li>Use <code>before</code> and <code>after</code> for ...
2521 <li>pre- or post-validation</li>
2522 <li>to add behavior to generated methods</li>
2525 <li>These two modifiers cannot change parameters or return values</li>
2530 <h1>Method Modifiers Summary</h1>
2533 <li>Use <code>around</code> to ...
2535 <li>alter parameters passed to the original method</li>
2536 <li>alter the return value of the original method</li>
2537 <li>not call the original method at all (or call a <em>different</em> method)</li>
2544 <h1>Method Modifiers Summary</h1>
2547 <li>When using modifiers in a role, require the modified method</li>
2548 <li>Use <code>augment</code> and <code>inner</code> to invert the normal subclassing flow ...
2550 <li>Least- to most-specific (parents to children)</li>
2551 <li>Build in "insertability" (stick more stuff in the "middle")</li>
2554 <li>Always call <code>inner</code> in the most specific subclass to allow for future extension</li>
2566 # perl bin/prove -lv \
2567 t/04-method-modifiers.t
2569 Iterate til this passes all its tests</pre>
2572 <div class="slide fake-slide0">
2573 <h1>Part 5: Types</h1>
2577 <h1>A Type System for Perl</h1>
2580 <li>Sort of ...</li>
2581 <li><em>Variables</em> are not typed</li>
2582 <li>Attributes can have types</li>
2583 <li>MooseX modules let you define method signatures</li>
2588 <h1>Components of a Moose Type</h1>
2591 <li>A type is a name and a constraint</li>
2592 <li>Types have a hierarchy</li>
2593 <li>Constraints are cumulative from parents</li>
2594 <li>Types can have associated coercions</li>
2599 <h1>Built-in Type Hierarchy</h1>
2617 <h1>Built-in Type Hierarchy</h1>
2651 <li>Like Perl's <code>if ($foo)</code></li>
2656 <h1>Value (and subtypes)</h1>
2659 <li><code>Value</code> is true when <code>! ref $thing</code></li>
2660 <li><code>Value</code> and <code>Str</code> are effectively the same, but <code>Str</code> is more expressive</li>
2661 <li><code>Num</code> is true when a <code>$scalar</code> looks like a number</li>
2662 <li>An overloaded object which numifies does not pass the <code>Num</code> constraint!</li>
2663 <li>Perl 5's overloading is hopelessly broken</li>
2668 <h1>ClassName and RoleName</h1>
2671 <li>A string with a package name</li>
2672 <li>The package <strong>must already be loaded</strong></li>
2677 <h1>Parameterizable Types</h1>
2680 <li>What does <code>ArrayRef[`a]</code> mean?</li>
2681 <li><code>s/`a/Int/</code> (or <code>Str</code> or ...)</li>
2682 <li>When you use it you can write ...
2684 <li><code>ArrayRef</code> (== <code>ArrayRef[Item]</code>)</li>
2685 <li><code>ArrayRef[Str]</code></li>
2686 <li><code>ArrayRef[MyTypeName]</code></li>
2687 <li><code>ArrayRef[HashRef[Maybe[Int]]]</code></li>
2697 <li>Maybe means either the named type or <code>undef</code></li>
2698 <li><code>Maybe[Int]</code> accepts integers or <code>undef</code></li>
2706 <li>This or that (or that or ...)</li>
2707 <li><code>Int | ArrayRef[Int]</code></li>
2708 <li>But use a coercion instead when possible</li>
2709 <li>Or use a <code>role_type</code>, <code>duck_type</code>, or anything not a union</li>
2710 <li>A union is often a code smell</li>
2715 <h1>Making Your Own Types</h1>
2717 <pre><code>use Moose::Util::TypeConstraints;
2719 <span class="incremental current">subtype 'PositiveInt',</span>
2720 <span class="incremental">as 'Int',</span>
2721 <span class="incremental">where { $_ > 0 },</span>
2722 <span class="incremental">message
2723 { "The value you provided ($_)"
2724 . " was not a positive int." };</span>
2728 <span class="incremental">isa => 'PositiveInt',</span>
2733 <h1>Automatic Types</h1>
2736 <li>Moose creates a type for every Moose class and role</li>
2737 <li>Unknown names are assumed to be classes</li>
2742 <h1>Automatic Types</h1>
2744 <pre><code>package Employee;
2749 <span class="highlight">isa => 'Employee',</span>
2752 has start_date => (
2754 <span class="highlight">isa => 'DateTime',</span>
2759 <h1>Subtype Shortcuts - <code>class_type</code></h1>
2761 <pre><code>use Moose::Util::TypeConstraints;
2762 class_type 'DateTime';</code></pre>
2766 <pre><code>subtype 'DateTime',
2768 where { $_->isa('DateTime') },
2769 message { ... };</code></pre>
2773 <h1>Subtype Shortcuts - <code>role_type</code></h1>
2775 <pre><code>use Moose::Util::TypeConstraints;
2776 role_type 'Printable';</coe></pre>
2780 <pre><code>subtype 'Printable',
2783 { Moose::Util::does_role(
2784 $_, 'Printable' ) },
2785 message { ... };</code></pre>
2789 <h1>Subtype Shortcuts - <code>duck_type</code></h1>
2791 <pre><code>use Moose::Util::TypeConstraints;
2792 duck_type Car => qw( run break_down );</code></pre>
2796 <pre><code>subtype 'Car',
2798 where { all { $_->can($_) }
2799 qw( run break_down ) },
2800 message { ... };</code></pre>
2804 <h1>Subtype Shortcuts - <code>enum</code></h1>
2806 <pre><code>use Moose::Util::TypeConstraints;
2807 enum Color => qw( red blue green ) );</code></pre>
2811 <pre><code>my %ok = map { $_ => 1 }
2812 qw( red blue green );
2817 message { ... };</code></pre>
2821 <h1>Anonymous Subtypes</h1>
2823 <pre><code>package Person;
2825 <span class="highlight">my $posint =
2826 subtype as 'Int', where { $_ > 0 };</span>
2830 <span class="highlight">isa => $posint,</span>
2834 <li>Shortcuts have anonymous forms as well</li>
2841 <pre><code>use Moose::Util::TypeConstraints;
2845 where { ! /[a-z]/ };</code></pre>
2851 <pre><code><span class="incremental current">coerce 'UCStr',</span>
2852 <span class="incremental">from 'Str',</span>
2853 <span class="incremental">via { uc };</span>
2855 has shouty_name => (
2858 <span class="incremental">coerce => 1,</span>
2863 <h1>Coercion Examples</h1>
2865 <pre><code>subtype 'My::DateTime',
2866 as class_type 'DateTime';
2868 coerce 'My::DateTime',
2870 via { DateTime->new( %{$_} ) };
2872 coerce 'My::DateTime',
2874 via { DateTime->from_epoch(
2875 epoch => $_ ) };</code></pre>
2878 <li>Use coercion to inflate a value</li>
2883 <h1>Coercion Examples</h1>
2885 <pre><code>coerce 'ArrayRef[Int]',
2887 via { [ $_ ] };</code></pre>
2890 <li>Instead of union - <code style="white-space: nowrap">Int | ArrayRef[Int]</code></li>
2895 <h1>Using Types with Attributes</h1>
2897 <pre><code>package Person;
2901 <span class="highlight">isa => 'Num',</span>
2904 has favorite_numbers => (
2906 <span class="highlight">isa => 'ArrayRef[Int]',
2907 coerce => 1,</span>
2912 <h1>More Droppings</h1>
2915 <li><code>Moose::Util::TypeConstraints</code> also needs cleanup</li>
2918 <pre><code>package Person;
2921 use Moose::Util::TypeConstraints;
2926 <span class="highlight">no Moose::Util::TypeConstraints;</span></code></pre>
2930 <h1>Typed Methods (Low-tech)</h1>
2932 <pre class="medium"><code>package Person;
2933 <span class="highlight">use MooseX::Params::Validate qw( validated_list );</span>
2937 <span class="highlight">my ( $tasks, $can_rest ) =
2941 { isa => 'ArrayRef[Task]',
2952 <h1>Typed Methods (High-tech)</h1>
2954 <pre class="medium"><code>package Person;
2956 <span class="highlight">use MooseX::Method::Signatures;</span>
2958 <span class="highlight">method work ( ArrayRef[Task] :$tasks,
2959 Bool :$can_rest = 0 )</span> {
2967 <h1>Digression: The Type Registry</h1>
2970 <li>Types are actually <code>Moose::Meta::TypeConstraints</code> <em>objects</em></li>
2971 <li>Stored in an interpreter-global registry mapping names to objects</li>
2979 <li>Coercions are attached to type objects</li>
2980 <li>Therefore also global</li>
2981 <li>Name conflicts between modules!</li>
2982 <li>Coercion conflicts between modules!</li>
2987 <h1>Namespace Fix</h1>
2990 <li>Use some sort of pseudo-namespacing scheme</li>
2991 <li>Never coerce directly to a class name, or <em>to</em> built-in types</li>
2996 <h1>Namespace Fix</h1>
2998 <pre><code>use Moose::Util::TypeConstraints;
2999 subtype <span class="highlight">'MyApp::Type::DateTime',</span>
3002 <span class="highlight">coerce 'MyApp::Type::DateTime',</span>
3004 via { DateTime->new( %{$_} ) }
3006 has creation_date => (
3008 <span class="highlight">isa => 'MyApp::Type::DateTime',</span>
3014 <h1>Namespace Fix</h1>
3016 <pre><code>subtype 'MyApp::Type::ArrayOfInt',
3019 coerce 'MyApp::Type::ArrayOfInt',
3021 via { [ $_ ] };</code></pre>
3025 <h1>Namespace Fix Pros and Cons</h1>
3028 <li><span class="right">Relatively simple</span></li>
3029 <li><span class="right">Already built into Moose</span></li>
3030 <li><span class="wrong">Conflates type and module namespaces</span></li>
3031 <li><span class="wrong">Type names are strings, so typos are easy to make and may be hard to find</span></li>
3036 <h1>MooseX::Types</h1>
3038 <pre><code>package MyApp::Types;
3041 <span class="highlight">-declare => [ qw( ArrayOfInt ) ]</span>;
3042 use MooseX::Types::Moose
3045 subtype <span class="highlight">ArrayOfInt</span>,
3048 coerce <span class="highlight">ArrayOfInt</span>
3050 via { [ $_ ] };</code></pre>
3054 <h1>MooseX::Types</h1>
3056 <pre><code>package MyApp::Account;
3058 use MyApp::Types qw( ArrayOfInt );
3060 has transaction_history => (
3067 <h1>MooseX::Types</h1>
3070 <li>Type names are exported functions, catches typos early</li>
3071 <li>Types must be pre-declared</li>
3072 <li>Types are stored with namespaces internally, but you use short names</li>
3073 <li>Import existing Moose types as functions from <code>MooseX::Types::Moose</code></li>
3074 <li>Still need string names for things like <code>ArrayRef['Email::Address']</code></li>
3079 <h1>MooseX::Types Pros and Cons</h1>
3082 <li><span class="right">Catches typos at compile time</span></li>
3083 <li><span class="right">Automatic namespacing</span></li>
3084 <li><span class="wrong">One more thing to install and learn</span></li>
3085 <li><span class="wrong">Every name is typed twice (declared and then defined)</span></li>
3086 <li><span class="wrong">Still stuck with strings when referring to class or role names</span></li>
3087 <li><span class="wrong">Coercion gotcha from earlier still applies to types exported from <code>MooseX::Types::Moose</code></span></li>
3092 <h1>Recommendation</h1>
3095 <li>Use <code>MooseX::Types</code></li>
3096 <li>Compile time error catching and automatic namespacing are huge wins</li>
3097 <li>Docs from <code>Moose::Util::TypeConstraints</code> are 98% compatible with <code>MooseX::Types</code> anyway</li>
3098 <li>A function exported by a type library works wherever a type name would</li>
3110 # perl bin/prove -lv t/05-types.t
3112 Iterate til this passes all its tests</pre>
3115 <div class="slide fake-slide0">
3116 <h1>Part 6: Advanced Attributes</h1>
3120 <h1>Weak References</h1>
3123 <li>A weak reference lets you avoid circular references</li>
3124 <li>Weak references do not increase the reference count</li>
3129 <h1>Circular Reference Illustrated</h1>
3131 <pre><code>my $foo = {};
3132 my $bar = { foo => $foo };
3133 $foo->{bar} = $bar;</code></pre>
3136 <li>Neither <code>$foo</code> nor <code>$bar</code> go out of scope<br />
3137 (until the program exits)</li>
3142 <h1>Weakening Circular References</h1>
3144 <pre><code>use Scalar::Util qw( weaken );
3147 my $bar = { foo => $foo };
3148 $foo->{bar} = $bar;
3149 weaken $foo->{bar}</code></pre>
3152 <li>When <code>$bar</code> goes out of scope, <code>$foo->{bar}</code> becomes <code>undef</code></li>
3157 <h1>Circular References in Attributes</h1>
3159 <pre><code>package Person;
3162 has name => ( is => 'ro' );
3163 has friend => ( is => 'rw' );
3165 my $alice = Person->new( name => 'Alice' );
3166 my $bob = Person->new( name => 'Bob' );
3167 $bob->friend($alice);
3168 $alice->friend($bob);</code></pre>
3174 <pre><code>package Person;
3177 has name => ( is => 'ro' );
3178 has friend => ( is => 'rw',
3179 <span class="highlight">weak_ref => 1</span> );
3181 my $alice = Person->new( name => 'Alice' );
3182 my $bob = Person->new( name => 'Bob' );
3183 $bob->friend($alice);
3184 $alice->friend($bob);</code></pre>
3188 <h1>Under the Hood</h1>
3191 <li>A <code>weak_ref</code> attribute calls <code>weaken</code> ...
3193 <li>during object construction</li>
3194 <li>when the attribute is set via a writer</li>
3204 <li>A code reference run after an attribute is <em>set</em></li>
3205 <li>Like an <code>after</code> modifier, but makes intentions clearer</li>
3208 <h2 class="wrong">Gross</h2>
3210 <pre><code>after salary_level => {
3212 <span class="highlight">return unless @_;</span>
3213 $self->clear_salary;
3218 <h1>Use a Trigger Instead</h1>
3220 <h2 class="right">Cleaner</h2>
3222 <pre><code>has salary_level => (
3225 sub { $_[0]->clear_salary },
3230 <h1>Trigger Arguments</h1>
3233 <li><code>$self</code></li>
3234 <li><code>$new_value</code></li>
3235 <li><code>$old_value</code> - if one exists</li>
3243 <li>Attributes can be objects</li>
3244 <li>Delegation transparently calls methods on those objects</li>
3249 <h1>Delegation Examples</h1>
3251 <pre><code>package Person;
3256 <span class="highlight">handles => [ 'inhale', 'exhale' ],</span>
3260 <li>Creates <code>$person->inhale</code> and <code>->exhale</code> methods</li>
3261 <li>Internally calls <code>$person->lungs->inhale</code></li>
3266 <h1>Why Delegation?</h1>
3269 <li>Reduce the number of classes exposed</li>
3270 <li>Re-arrange class internals -<br />
3271 turn a method into an attribute with delegation</li>
3272 <li>Provide convenenience methods</li>
3277 <h1>Moose's <code>handles</code> Parameter</h1>
3280 <li>Accepts many arguments ...
3282 <li>Array reference - list of methods to delegate as-is</li>
3283 <li>Hash reference - map of method names</li>
3284 <li>Regex - delegates all matching methods</li>
3285 <li>Role name - delegates all methods in the role</li>
3286 <li>Sub reference - does something complicated ;)</li>
3293 <h1>Array Reference</h1>
3296 <li>1-to-1 mapping</li>
3297 <li>Takes each method name and creates a simple delegation from the delegating class to the delegatee attribute</li>
3302 <h1>Hash Reference</h1>
3305 <li>Mapping of names in the delegating class to the delegatee class</li>
3308 <pre><code>package Person;
3312 isa => 'BankAccount',
3313 <span class="highlight">handles => {
3314 receive_money => 'deposit',
3315 give_money => 'withdraw',
3321 <h1>Hash Reference Detailed</h1>
3323 <pre><code> handles => {
3324 receive_money => 'deposit',
3325 give_money => 'withdraw',
3329 <li><code>$person->receive_money</code> = <code>$person->account->deposit</code></li>
3330 <li><code>$person->give_money</code> = <code>$person->account->withdraw</code></li>
3337 <pre><code>package Person;
3343 handles => qr/.*/,
3347 <li>Creates a delegation for every method in the Name class</li>
3348 <li>Excludes <code>meta</code> and methods inherited from <code>Moose::Object</code></li>
3355 <pre><code>package Auditor;
3357 sub record_change { ... }
3358 sub change_history { ... }
3365 does => 'Auditor',
3366 <span class="highlight">handles => 'Auditor',</span>
3371 <h1>Role Name Detailed</h1>
3374 <li>Account gets delegate methods for each method in the <code>Auditor</code> role
3376 <li>record_history</li>
3377 <li>change_history</li>
3384 <h1>Native Delegation</h1>
3387 <li>Delegate to <em>unblessed</em> Perl types</li>
3388 <li>Scalar, array or hash ref, etc</li>
3389 <li>Treat Perl types as objects</li>
3390 <li>Still uses <code>handles</code></li>
3391 <li>Pretend that native Perl types have methods</li>
3396 <h1>Native Delegation - Array(Ref)</h1>
3399 <li>Methods include:
3401 <li><code>push</code></li>
3402 <li><code>shift</code></li>
3403 <li><code>elements</code> - returns all elements</li>
3404 <li><code>count</code></li>
3405 <li><code>is_empty</code></li>
3406 <li>quite a few more</li>
3413 <h1>Native Delegation - Array(Ref)</h1>
3415 <pre><code>package Person;
3417 has _favorite_numbers => (
3418 traits => [ 'Array' ],
3420 isa => 'ArrayRef[Int]',
3421 default => sub { [] },
3422 init_arg => undef,
3423 <span class="highlight">handles =>
3424 { favorite_numbers => 'elements',
3425 add_favorite_number => 'push',
3431 <h1>Native Delegation - Array(Ref)</h1>
3433 <pre><code>my $person = Person->new();
3435 $person->add_favorite_number(7);
3436 $person->add_favorite_number(42);
3439 for $person->favorite_numbers;
3446 <h1>Native Delegation</h1>
3449 <li>Native types are ...
3451 <li>Number - <code>add</code>, <code>mul</code>, ...</li>
3452 <li>String - <code>append</code>, <code>chop</code>, ...</li>
3453 <li>Counter - <code>inc</code>, <code>dec</code>, ...</li>
3454 <li>Bool - <code>set</code>, <code>toggle</code>, ...</li>
3455 <li>Hash - <code>get</code>, <code>set</code>, ...</li>
3456 <li>Array - already saw it</li>
3457 <li>Code - <code>execute</code> and <code>execute_method</code></li>
3464 <h1>Curried Delegation</h1>
3467 <li>A delegation with some preset arguments</li>
3468 <li>Works with object or Native delegation</li>
3473 <h1>Curried Delegation</h1>
3475 <pre><code>package Person;
3479 isa => 'BankAccount',
3482 <span class="highlight">[ 'deposit', 100 ]</span>
3484 <span class="highlight">[ 'withdraw', 100 ]</span>
3490 <h1>Curried Delegation</h1>
3492 <pre><code>$person->receive_100;
3494 $person->account->deposit(100);</code></pre>
3498 <h1>Traits and Metaclasses</h1>
3501 <li>The ultimate in customization</li>
3502 <li>Per attribute metaclasses</li>
3503 <li>Per attribute roles applied to the attribute metaclass</li>
3504 <li>Change the meta-level behavior</li>
3509 <h1>Traits and Metaclasses</h1>
3512 <li>The default metaclass is <code>Moose::Meta::Attribute</code></li>
3513 <li>Controls accessor generation, defaults, delegation, etc.</li>
3514 <li>Adding a role to this metaclass (or replacing it) allows for infinite customization</li>
3519 <h1>Traits and Metaclasses</h1>
3522 <li>Can add/alter/remove an attribute parameter (from <code>has</code>)</li>
3523 <li>Can change behavior of created attribute</li>
3528 <h1>Simple Trait Example</h1>
3530 <pre><code>package Person;
3532 use MooseX::LabeledAttributes;
3535 <span class="highlight">traits => [ 'Labeled' ],</span>
3538 <span class="highlight">label => 'Social Security Number',</span>
3540 print <span class="highlight">Person->meta
3541 ->get_attribute('ssn')->label;</span></code></pre>
3545 <h1>Simple Metaclass Example</h1>
3547 <pre><code>package Person;
3549 use MooseX::LabeledAttributes;
3552 <span class="highlight">metaclass =>
3553 'MooseX::Meta::Attribute::Labeled',</span>
3556 <span class="highlight">label => 'Social Security Number',</span>
3558 print <span class="highlight">Person->meta
3559 ->get_attribute('ssn')->label;</span></code></pre>
3563 <h1>Traits vs Metaclass</h1>
3566 <li>Can apply any mix of traits to an attribute</li>
3567 <li>But just one metaclass</li>
3568 <li>Traits (aka roles) can cooperate</li>
3569 <li>Metaclasses require you to pick just one</li>
3574 <h1>Advanced Attributes Summary</h1>
3577 <li>Use <code>weak_ref</code> to avoid circular references</li>
3578 <li>Use trigger to do an action post-attribute write</li>
3579 <li>Use delegations to hide "internal" objects</li>
3580 <li>Traits and metaclasses let you extend Moose's core attribute features</li>
3592 # perl bin/prove -lv \
3593 t/06-advanced-attributes.t
3595 Iterate til this passes all its tests</pre>
3598 <div class="slide fake-slide0">
3599 <h1>Part 7: Introspection</h1>
3602 <div class="slide fake-slide0">
3603 <h1>Part 8: A Brief Tour of MooseX</h1>
3607 <h1>Notable MX Modules on CPAN</h1>
3610 <li><strong>Not comprehensive</strong></li>
3611 <li>152 MooseX distributions on CPAN as of 02/02/2010</li>
3612 <li>Some of them are crap</li>
3617 <h1>Already Mentioned Several</h1>
3620 <li><code>MooseX::NonMoose</code> - best solution for subclassing non-Moose parents</li>
3621 <li><code>MooseX::Declare</code> - <em>real</em> Perl 5 OO</li>
3622 <li><code>MooseX::FollowPBP</code> and <code>MooseX::SemiAffordanceAccessor</code></li>
3623 <li><code>MooseX::Params::Validate</code> and <code>MooseX::Method::Signatures</code></li>
3624 <li><code>MooseX::Types</code></li>
3629 <h1>MooseX::Declare</h1>
3631 <pre><code>use MooseX::Declare;
3632 use 5.10.0; # for say
3636 ( is => 'ro', isa => 'Str' );
3639 say $self->greeting;
3645 <h1>MooseX::Declare</h1>
3648 <li>Still experimental-ish, but seeing more and more use</li>
3649 <li><strong>Not</strong> a source filter!</li>
3650 <li>Hooks into the Perl parser rather than filtering all your code</li>
3651 <li>But not supported by <code>PPI</code>, <code>perltidy</code>, etc.</li> (yet?)
3656 <h1>MooseX::StrictConstructor</h1>
3659 <li>By default, unknown constructor arguments are ignored</li>
3660 <li>MX::StrictConstructor turns these into an error</li>
3665 <h1>MooseX::StrictConstructor</h1>
3667 <pre><code>package Person;
3670 <span class="highlight">use MooseX::StrictConstructor;</span>
3672 has name => ( is => 'ro' );
3675 ( na<span class="wrong">n</span>e => 'Ringo Shiina' ); # kaboom</code></pre>
3679 <h1>MooseX::Traits</h1>
3682 <li>Combines object construction and role application</li>
3683 <li>Makes it easy to create one-off customized objects</li>
3688 <h1>MooseX::Traits</h1>
3690 <pre><code>package MyApp::Thingy;
3693 <span class="highlight">with 'MooseX::Traits';</span>
3696 MyApp::Thingy-><span class="highlight">new_with_traits</span>
3697 ( <span class="highlight">traits => [ 'Foo', 'Bar' ],</span>
3698 size => 42 );</code></pre>
3702 <h1>MooseX::Getopt</h1>
3705 <li>Makes command-line interface programs easy!</li>
3706 <li>Construct an object from CLI arguments</li>
3711 <h1>MooseX::Getopt</h1>
3713 <pre><code>package App::CLI;
3716 <span class="highlight">with 'MooseX::Getopt';</span>
3719 ( is => 'ro', required => 1 );
3721 ( is => 'ro', isa => 'ArrayRef[Str]' );
3723 sub run { ... }</code></pre>
3727 <h1>MooseX::Getopt</h1>
3730 <li>Then call it like this:</li>
3733 <pre><code>#!/usr/bin/perl
3737 <span class="highlight">App::CLI->new_with_options()</span>->run();</code></pre>
3741 --filters compress \
3742 --filters sanitize</pre>
3746 <h1>MooseX::Clone</h1>
3748 <pre><code>package Person;
3751 <span class="highlight">with 'MooseX::Clone';</span>
3753 my $person = Person->new;
3754 my $clone = <span class="highlight">$person->clone;</span></code></pre>
3758 <h1>MooseX::NonMoose</h1>
3761 <li>Highly recommended for subclassing non-Moose parents</li>
3762 <li>Gets all the little annoying details right</li>
3767 <h1>MooseX::Role::Parameterized</h1>
3769 <pre><code>package HasCollection;
3770 <span class="current incremental">use MooseX::Role::Parameterized;</span>
3771 <span class="incremental">parameter type => ( isa => 'Str',
3772 default => 'Item' );</span>
3773 <span class="incremental">role {
3777 'ArrayRef[' . $p->type() . ']';
3778 has collection =>
3781 };</span></code></pre>
3785 <h1>MooseX::Role::Parameterized</h1>
3787 <pre><code>package Person;
3790 with HasCollection => { type => 'Int' };</code></pre>
3797 <div class="slide fake-slide0">
3798 <h1>Part 9: Writing Moose Extensions</h1>
3801 <div class="slide fake-slide0">
3806 <h1>More Information</h1>
3809 <li><a href="http://moose.perl.org/">http://moose.perl.org/</a></li>
3810 <li><a href="http://search.cpan.org/dist/Moose/lib/Moose/Manual.pod">Moose::Manual</a> and <a href="http://search.cpan.org/dist/Moose/lib/Moose/Cookbook.pod">Moose::Cookbook</a></li>
3811 <li><a href="irc://irc.perl.org/#moose">irc://irc.perl.org/#moose</a></li>
3812 <li>mailing list - <a href="mailto:moose@perl.org">moose@perl.org</a></li>
3813 <li>Slides and exercises are in Moose's git repo:
3815 <span style="font-size:80%; white-space: nowrap">git://jules.scsys.co.uk/gitmo/moose-presentations</span></li>
3825 Copyright 2009 David Rolsky. All Rights Reserved.
3827 This work is licensed under a Creative Commons Attribution-Share Alike
3828 3.0 United States License See
3829 http://creativecommons.org/licenses/by-sa/3.0/us/ for details.