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 (188 MooseX::* on CPAN)</li>
75 <li>Community approved (1200+ downstream dependents on CPAN)</li>
80 <h1>Moose Background</h1>
83 <li>Created by Stevan Little, first released in 2006</li>
84 <li>Moose builds on Perl 5's native OO</li>
85 <li>Borrows ideas from other languages, notably Perl 6</li>
86 <li>Provides semantics for common operations</li>
90 <div class="slide fake-slide0">
91 <h1>Part 0: Moose Concepts</h1>
103 <li>Superclasses</li>
104 <li>Method modifiers</li>
105 <li>Constructor and destructor</li>
106 <li>One metaclass object</li>
109 <li>Classes do roles</li>
114 <h1>Class Example</h1>
116 <pre><code>package Person;
117 <span class="highlight">use Moose;</span></code></pre>
120 <li>Poof, a Moose-based class!</li>
128 <li>Aka property, slot, field, member variable</li>
129 <li>A piece of data owned by an object</li>
140 <li>Mutability (read-only vs read-write)</li>
141 <li>An optional type</li>
142 <li>Accessor methods</li>
143 <li>Delegation methods</li>
144 <li>Optional default value</li>
145 <li>Many more features</li>
148 <li>Stored in the object, but don't worry about that</li>
153 <h1>Attribute Example</h1>
155 <pre><code>package Person;
158 <span class="highlight">has first_name => ( is => 'ro' );</span></code></pre>
166 <li>Nothing fancy here, just Perl subroutines</li>
169 <pre><code>package Person;
172 <span class="highlight">sub greet { ... }</span></code></pre>
179 <li>Classes <strong>do</strong> (or consume) roles</li>
180 <li>Similar to mixins and Java interfaces</li>
188 <li>Like classes, can have attributes, methods, do roles</li>
189 <li>Roles can require methods</li>
190 <li>Roles are composed (flattened) into classes</li>
195 <h1>Role Example</h1>
197 <pre><code>package HasPermissions;
198 <span class="highlight">use Moose::Role;</span>
200 has is_admin => ( is => 'rw' );</code></pre>
204 <h1>Role Example</h1>
210 <pre><code>package Person;
213 <span class="highlight">with 'HasPermissions';</span></code></pre>
217 <h1>Method Modifiers</h1>
221 <li>"<strong>Before</strong> foo(), do this first"</li>
222 <li>"Do this <strong>after</strong> foo()"</li>
223 <li>"Put this code <strong>around</strong> foo()"</li>
228 <h1>Before and After</h1>
230 <pre><code>before 'foo'
231 => sub { warn 'About to call foo()' };
234 => sub { warn 'Leaving foo()' };</code></pre>
241 <pre><code>around 'foo' => sub {
242 my $real_foo = shift;
245 warn 'Just before foo()';
247 $self->$real_foo( @_, bar => 42 );
251 'modify return values'
257 <h1>Type Constraints</h1>
260 <li>NOT A FULL-BLOWN TYPE SYSTEM!</li>
261 <li>But still darn useful</li>
262 <li>Constrain attribute values</li>
263 <li>Coerce from other types</li>
268 <h1>Type Constraint Example</h1>
270 <pre><code>package Person;
275 <span class="highlight">isa => 'Int'</span>,
279 Person->new( weight => 'heavy' );</code></pre>
286 <li>Attributes can define delegations</li>
287 <li>Lets you hide some implementation details</li>
288 <li>Fewer objects to chase around</li>
295 <pre><code>package Person;
301 <span class="highlight">handles => { 'blog_host' => 'host' },</span>
304 <span class="highlight">$person->blog_host;</span>
305 # really calls $person->blog_uri->host</code></pre>
309 <h1>Constructors</h1>
312 <li>Moose creates <code>new()</code> for you</li>
313 <li>Provide an optional <code>BUILDARGS()</code> and <code>BUILD()</code></li>
321 <li>Provide an optional <code>DEMOLISH()</code></li>
326 <h1>Moose Meta-API</h1>
329 <li>Answers questions like ...
331 <li>What methods does this class have?</li>
332 <li>What are its parents?</li>
333 <li>What attributes does it have (including inherited attributes)?</li>
334 <li>What roles does it do?</li>
335 <li>Much, much, more</li>
342 <h1>Moose Meta-API</h1>
345 <li>Not just for introspection ...
347 <li>Add methods, attributes, roles, etc</li>
348 <li>Extend and alter core features</li>
358 <li>A quick bit of propaganda ...</li>
365 <pre><code>package Person;
368 has last_name => (
375 <h1>Without Moose</h1>
377 <pre class="small"><code>package Person;
387 if (exists $args{last_name}) {
388 confess "Attribute (last_name) does not pass the type constraint because: "
389 . "Validation failed for 'Str' with value $args{last_name}"
390 if ref($args{last_name});
391 $self->{last_nane} = $args{last_name};
394 return bless $self, $class;
402 confess "Attribute (last_name) does not pass the type constraint because: "
403 . "Validation failed for 'Str' with value $value"
405 $self->{last_name} = $value;
408 return $self->{last_name};
414 <h1>Side by side</h1>
416 <table class="side-by-side">
419 <pre><code>package Person;
422 has last_name => (
428 <pre class="small"><code>package Person;
438 if (exists $args{last_name}) {
439 confess "Attribute (last_name) does not pass the type constraint because: "
440 . "Validation failed for 'Str' with value $args{last_name}"
441 if ref($args{last_name});
442 $self->{last_nane} = $args{last_name};
445 return bless $self, $class;
453 confess "Attribute (last_name) does not pass the type constraint because: "
454 . "Validation failed for 'Str' with value $value"
456 $self->{last_name} = $value;
459 return $self->{last_name};
468 <h1>Side by side</h1>
470 <table class="side-by-side">
473 <pre><code><span class="match-moose">package Person;</span>
476 has last_name => (
482 <pre class="small"><code><span class="match-unsweet">package Person;</span>
492 if (exists $args{last_name}) {
493 confess "Attribute (last_name) does not pass the type constraint because: "
494 . "Validation failed for 'Str' with value $args{last_name}"
495 if ref($args{last_name});
496 $self->{last_nane} = $args{last_name};
499 return bless $self, $class;
507 confess "Attribute (last_name) does not pass the type constraint because: "
508 . "Validation failed for 'Str' with value $value"
510 $self->{last_name} = $value;
513 return $self->{last_name};
521 <h1>Side by side</h1>
523 <table class="side-by-side">
526 <pre><code>package Person;
527 <span class="match-moose">use Moose;</span>
529 has last_name => (
535 <pre class="small"><code>package Person;
536 <span class="match-unsweet">use strict;
543 my $self = {};</span>
545 if (exists $args{last_name}) {
546 confess "Attribute (last_name) does not pass the type constraint because: "
547 . "Validation failed for 'Str' with value $args{last_name}"
548 if ref($args{last_name});
549 $self->{last_nane} = $args{last_name};
552 <span class="match-unsweet">return bless $self, $class;
560 confess "Attribute (last_name) does not pass the type constraint because: "
561 . "Validation failed for 'Str' with value $value"
563 $self->{last_name} = $value;
566 return $self->{last_name};
574 <h1>Side by side</h1>
576 <table class="side-by-side">
579 <pre><code>package Person;
582 <span class="match-moose">has last_name => (</span>
585 <span class="match-moose">);</span></code></pre>
588 <pre class="small"><code>package Person;
598 <span class="match-unsweet">if (exists $args{last_name}) {</span>
599 confess "Attribute (last_name) does not pass the type constraint because: "
600 . "Validation failed for 'Str' with value $args{last_name}"
601 if ref($args{last_name});
602 <span class="match-unsweet">$self->{last_nane} = $args{last_name};
605 return bless $self, $class;
613 confess "Attribute (last_name) does not pass the type constraint because: "
614 . "Validation failed for 'Str' with value $value"
616 $self->{last_name} = $value;
619 return $self->{last_name};
627 <h1>Side by side</h1>
629 <table class="side-by-side">
632 <pre><code>package Person;
635 has last_name => (
636 <span class="match-moose">is => 'rw',</span>
641 <pre class="small"><code>package Person;
651 if (exists $args{last_name}) {
652 confess "Attribute (last_name) does not pass the type constraint because: "
653 . "Validation failed for 'Str' with value $args{last_name}"
654 if ref($args{last_name});
655 $self->{last_nane} = $args{last_name};
658 return bless $self, $class;
661 <span class="match-unsweet">sub last_name {
665 my $value = shift;</span>
666 confess "Attribute (last_name) does not pass the type constraint because: "
667 . "Validation failed for 'Str' with value $value"
669 <span class="match-unsweet">$self->{last_name} = $value;
672 return $self->{last_name};
673 }</span></code></pre>
680 <h1>Side by side</h1>
682 <table class="side-by-side">
685 <pre><code>package Person;
688 has last_name => (
690 <span class="match-moose">isa => 'Str',</span>
694 <pre class="small"><code>package Person;
704 if (exists $args{last_name}) {
705 <span class="match-unsweet">confess "Attribute (last_name) does not pass the type constraint because: "
706 . "Validation failed for 'Str' with value $args{last_name}"
707 if ref($args{last_name});</span>
708 $self->{last_nane} = $args{last_name};
711 return bless $self, $class;
719 <span class="match-unsweet">confess "Attribute (last_name) does not pass the type constraint because: "
720 . "Validation failed for 'Str' with value $value"
721 if ref($value);</span>
722 $self->{last_name} = $value;
725 return $self->{last_name};
733 <h1>Side by side</h1>
735 <table class="side-by-side">
736 <tr class="incremental">
740 <tr class="incremental">
741 <td>92 characters</td>
742 <td>741 characters</td>
746 <pre><code>package Person;
749 has last_name => (
755 <pre class="small"><code>package Person;
765 if (exists $args{last_name}) {
766 confess "Attribute (last_name) does not pass the type constraint because: "
767 . "Validation failed for 'Str' with value $args{last_name}"
768 if ref($args{last_name});
769 $self->{last_nane} = $args{last_name};
772 return bless $self, $class;
780 confess "Attribute (last_name) does not pass the type constraint because: "
781 . "Validation failed for 'Str' with value $value"
783 $self->{last_name} = $value;
786 return $self->{last_name};
796 <pre class="small"><code>sub new {
801 if (exists $args{last_name}) {
802 confess "Attribute (last_name) does not pass the type constraint because: "
803 . "Validation failed for 'Str' with value $args{last_name}"
804 if ref($args{last_name});
805 $self->{last_nane} = $args{last_name};
808 return bless $self, $class;
815 <pre class="small"><code>if (exists $args{last_name}) {
816 confess "Attribute (last_name) does not pass the type constraint because: "
817 . "Validation failed for 'Str' with value $args{last_name}"
818 if ref($args{last_name});
819 $self->{last_nane} = $args{last_name};
826 <code>$self->{last_nane} = $args{last_name};</code>
831 <code>$self->{last_na<span class="wrong">n</span>e}</code>
837 <pre><code>package Person;
840 has last_name => (
847 <h1>More Why Moose?</h1>
850 <li>Less code == fewer bugs</li>
851 <li>Moose is well-tested, test your own code, not Moose</li>
852 <li>Focus on <strong>what</strong>, not <strong>how</strong></li>
856 <div class="slide fake-slide0">
857 <h1>Part 1: Moose Classes</h1>
861 <h1>Moose Classes</h1>
864 <li>Moose classes are Perl packages which <code>use Moose</code></li>
869 <h1>Moose.pm and Your Class</h1>
871 <pre><code>package Person;
872 use Moose;</code></pre>
875 <li><code>Moose.pm</code> provides declarative sugar</li>
876 <li>Turns on <code>strict</code> and <code>warnings</code></li>
877 <li>Creates metaclasses for your class: <code>Person->meta</code></li>
878 <li>Moose classes automatically inherit from <code>Moose::Object</code></li>
883 <h1>What <code>Moose::Object</code> Provides</h1>
886 <li>Constructor - <code>new()</code></li>
887 <li>Calls your <code>BUILDARGS()</code> and/or <code>BUILD()</code></li>
888 <li>Calls your <code>DEMOLISH</code> during object destruction</li>
896 <li>Processes <code>new</code>'s <code>@_</code>, returns a hash reference of attribute name/value pairs</li>
897 <li>Accepts a hash or hashref; errors otherwise</li>
898 <li>Provide your own for other cases</li>
899 <li><strong>Always</strong> call <code>$class->SUPER::BUILDARGS(@_)</code> as a fallback!</li>
904 <h1>BUILDARGS Example</h1>
906 <pre><code>package Person;
912 if ( @_ == 1 && ! ref $_[0] ) {
913 <span class="highlight">return { ssn => $_[0] };</span>
915 <span class="highlight">return $class->SUPER::BUILDARGS(@_)</span>;
918 <span class="highlight">Person->new('123-45-6789')</span></code></pre>
925 <li>Called after object is created, before <code>new</code> returns</li>
926 <li>Chance to do more complex validation, set complex attributes</li>
927 <li>Called in reverse inheritance order, parents to children</li>
928 <li>Return value is ignored</li>
933 <h1>BUILD Example</h1>
935 <pre><code>package Person;
941 if ( $self->country_of_residence
943 die 'All US residents'
944 . ' must have an SSN'
945 unless $self->has_ssn;
951 <h1>Object Construction a la Moose</h1>
953 <pre><code>Person->new(@_)</code></pre>
955 <ol style="margin-top: 0">
956 <li>Calls <code>Person->BUILDARGS(@_)</code> to turn <code>@_</code> into a hashref</li>
957 <li>Blesses a reference</li>
958 <li>Populates attributes based on the hashref from #1</li>
959 <li>Calls <code>$new_object->BUILDALL($constructor_args)</code>
960 <br />... which calls all <code>BUILD</code> methods</li>
961 <li>Returns the object</li>
966 <h1>The Object is Opaque</h1>
969 <li>Technically it's a hash reference</li>
970 <li><span class="wrong">If you <em>ever</em> treat it as one <strong>you are doing it wrong!</strong></span></li>
971 <li>Moose probably provides a feature to do what you need</li>
979 <li>Like <code>DESTROY</code>, but Moose makes sure all <code>DEMOLISH</code> methods in a hierarchy are called</li>
980 <li>Called in normal inheritance order, children to parents</li>
981 <li><em>Never</em> called by you, only by Perl itself</li>
989 <li><code>extends</code> is sugar for declaring parent classes</li>
990 <li>Also ensures metaclass compatibility between parent and child</li>
991 <li>Do not <code>use base</code></li>
994 <pre><code>package Employee;
996 <span class="highlight">extends 'Person';</span></code></pre>
1003 <li>Each call to <code>extends</code> <strong>resets</strong> your parents</li>
1006 <h2 class="wrong">Wrong</h2>
1008 <pre><code>package EvilEmployee;
1011 extends 'Thief';</code></pre>
1013 <h2 class="right">Right</h2>
1015 <pre><code>package EvilEmployee;
1017 extends 'Person', 'Thief';</code></pre>
1021 <h1>Extending un-Moose-y Parents</h1>
1023 <pre><code>package My::LWP;
1025 extends 'LWP';</code></pre>
1028 <li>No <code>Moose::Object</code>, so ...
1030 <li>No attribute-handling <code>new()</code></li>
1031 <li>No <code>BUILDARGS()</code> or <code>BUILD()</code></li>
1032 <li>No <code>DEMOLISH()</code></li>
1035 <li>But see <code>MooseX::NonMoose</code> for a workaround</li>
1040 <h1><code>override</code> and <code>super</code></h1>
1043 <li><code>override</code> is another method modifier</li>
1044 <li>An alternative to Perl's <code>SUPER::</code></li>
1045 <li><em>Declares</em> your intent to override a method</li>
1050 <h1><code>override</code> and <code>super</code></h1>
1052 <pre><code>package Employee;
1055 <span class="current incremental">extends 'Person';</span>
1057 <span class="incremental">override</span> <span class="incremental">work</span> <span class="incremental">=> sub {
1061 unless $self->got_paid;
1063 }</span><span class="incremental">;</span></code></pre>
1067 <h1>Caveat <code>super</code></h1>
1070 <li>Mostly like <code>$self->SUPER::work(@_)</code></li>
1071 <li><strong>But</strong> cannot change <code>@_</code>!</li>
1072 <li>Binds the parent's method <strong>correctly</strong> at compile time</li>
1073 <li>Parent determined by checking <code>Child->meta()->superclasses()</code></li>
1078 <h1>Minimal Attributes</h1>
1081 <li><code>has 'foo'</code></li>
1082 <li>Use <code>is => 'ro'</code> or <code>is => 'rw'</code></li>
1083 <li>Attributes without "is" have no accessors</li>
1088 <h1>Read-write attributes</h1>
1090 <pre><code>package Person;
1093 has first_name => ( <span class="highlight">is => 'rw'</span> );
1096 Person->new( first_name => 'Dave' );
1098 $person->first_name('Stevan');
1099 print $person->first_name; # Stevan</code></pre>
1104 <h1>Read-only attributes</h1>
1106 <pre><code>package Person;
1109 has first_name => ( <span class="highlight">is => 'ro'</span> );
1112 Person->new( first_name => 'Dave' );
1114 $person->first_name('Stevan'); # dies</code></pre>
1119 <h1>There is More to Come</h1>
1122 <li>Attributes have a <em>lot</em> of features</li>
1127 <h1>Cleaning Up Moose Droppings</h1>
1129 <pre><code>package Person;
1133 Person->can('extends');</code></pre>
1136 <li>Not very hygienic</li>
1141 <h1>Cleaning Up Moose Droppings</h1>
1143 <pre><code>package Person;
1148 <span class="highlight">no Moose;</span>
1151 Person->can('extends');</code></pre>
1155 <h1>Cleaning Up Moose Droppings</h1>
1157 <pre><code>package Person;
1158 <span class="highlight">use namespace::autoclean;</span>
1164 Person->can('extends');</code></pre>
1171 <li>Cleaning up is a best practice</li>
1172 <li>Say <code>no Moose</code> at the end of a package</li>
1173 <li>Or <code>use namespace::autoclean</code> at the top</li>
1179 <h1>Immutability</h1>
1182 <li><span style="font-family: URW Chancery L; font-size: 120%">Stevan's Incantation of Fleet-Footedness</span></li>
1185 <pre><code>package Person;
1188 <span class="highlight">__PACKAGE__->meta->make_immutable;</span></code></pre>
1192 <h1>What <code>make_immutable</code> does</h1>
1196 <li>Uses <code>eval</code> to "inline" a constructor</li>
1197 <li>Memoizes a lot of meta-information</li>
1198 <li>Makes loading your class slower</li>
1199 <li>Makes object creation <em>much</em> faster</li>
1204 <h1>When to Immutabilize?</h1>
1207 <li><em>Almost</em> always</li>
1208 <li>Startup time vs execution time</li>
1213 <h1>Classes Summary</h1>
1216 <li><code>use Moose</code></li>
1217 <li><code>Class->meta</code></li>
1218 <li><code>Moose::Object</code> base class</li>
1219 <li><code>extends</code>, <code>override</code>, and <code>super</code></li>
1220 <li>Simple attributes: <code>has</code>, <code>is => 'ro'</code>, & <code>is => 'rw'</code></li>
1221 <li><code>no Moose</code></li>
1222 <li><code>__PACKAGE__->meta->make_immutable</code></li>
1235 # perl bin/prove -lv t/00-prereq.t
1237 # perl install-moose (if needed)
1239 ## Read the instructions in t/01-classes.t
1241 # perl bin/prove -lv t/01-classes.t
1243 # edit lib/Person.pm and lib/Employee.pm
1245 Iterate til this passes all its tests</pre>
1248 <div class="slide fake-slide0">
1249 <h1>Part 2: Roles</h1>
1253 <h1>Just What Is a Role?</h1>
1256 <li>Mixin? Interface? Trait?</li>
1257 <li>Yes ... and more!</li>
1262 <h1>Roles - State <strong>and</strong> Behavior</h1>
1264 <pre><code>package HasPermissions;
1266 <span class="current incremental"># state
1267 has access_level => ( is => 'rw' );</span>
1269 <span class="incremental"># behavior
1272 my $required = shift;
1274 return $self->access_level
1276 }</span></code></pre>
1281 <h1>Roles Can Define Interfaces</h1>
1283 <pre><code>package Printable;
1286 requires 'as_string';</code></pre>
1290 <h1>Roles Can Do All Three</h1>
1292 <pre><code>package Printable;
1295 requires 'as_string';
1297 has has_been_printed => ( is => 'rw' );
1301 print $self->as_string;
1302 $self->has_been_printed(1);
1307 <h1>Classes Consume Roles</h1>
1309 <pre><code>package Person;
1312 with 'Printable';</code></pre>
1316 <h1>Classes Consume Roles</h1>
1318 <pre><code>package Person;
1320 sub as_string { $_[0]->first_name() }
1324 my $person = Person->new(
1325 first_name => 'Kenichi',
1326 last_name => 'Asai',
1327 access_level => 42,
1330 $person->print();</code></pre>
1334 <h1>Roles in Practice</h1>
1337 <li>Consuming a role =~ inlining the role</li>
1342 <h1>In Other Words ...</h1>
1344 <pre><code>package Person;
1347 <span class="highlight">with 'Printable';</span></code></pre>
1351 <h1>In Other Words ...</h1>
1353 <pre><code>package Person;
1356 <span class="delete">with 'Printable';</span>
1358 <span class="highlight">has has_been_printed => ( is => 'rw' );
1362 print $self->as_string;
1363 $self->has_been_printed(1);
1364 }</span></code></pre>
1371 <li>Role consumption is introspectable</li>
1374 <pre><code>if ( Person->does('Printable') ) { ... }
1378 Person->meta->does_role('Printable')</code></pre>
1383 <h1>These Names Are the Same</h1>
1386 <li>What if a role and class define the same method?</li>
1387 <li>A class's <em>local</em> methods win over the role's</li>
1388 <li>The role's methods win over the class's <em>inherited</em> methods</li>
1393 <h1>Conflicts Between Roles</h1>
1396 <li>Two roles with a method of the same name</li>
1397 <li>Generates a compile-time error when consumed by a class</li>
1402 <h1>Conflict Example</h1>
1404 <pre><code>package IsFragile;
1409 package CanBreakdance;
1412 sub break { ... }</code></pre>
1416 <h1>Conflict Example</h1>
1418 <pre><code>package FragileDancer;
1421 <span class="highlight">with 'IsFragile', 'CanBreakdance';</span></code></pre>
1424 <li>Only one <code>with</code>!</li>
1429 <h1>Conflict Resolution</h1>
1432 <li>The consuming class must resolve the conflict by implementing the method</li>
1433 <li>Can use some combination of method exclusion and aliasing</li>
1438 <h1>Conflicts Are a Smell</h1>
1441 <li>Roles are about semantics!</li>
1442 <li>Roles have a <em>meaning</em></li>
1443 <li>Method name conflicts smell like bad design</li>
1448 <h1>Roles With Roles</h1>
1450 <pre><code>package Comparable;
1453 requires 'compare';</code></pre>
1457 <h1>Roles With Roles</h1>
1459 <pre><code>package TestsEquality;
1466 return $self->compare(@_) == 0;
1471 <h1>And then ...</h1>
1473 <pre><code>package Integer;
1476 with 'TestsEquality';
1478 # Satisfies the Comparable role
1481 Integer->does('TestsEquality'); # true
1482 Integer->does('Comparable'); # also true!</code></pre>
1486 <h1>Name Conflicts Between Roles</h1>
1488 <pre><code>package HasSubProcess;
1491 <span class="highlight">sub execute { ... }</span>
1496 with 'HasSubProcess';
1498 <span class="highlight">sub execute { ... }</span></code></pre>
1502 <h1>Delayed Conflict</h1>
1504 <pre><code>package SysadminAssassin;
1505 with 'Killer';</code></pre>
1508 <li><code>SysadminAssassin</code> must implement its own <code>execute</code></li>
1509 <li>But loading the <code>Killer</code> role by itself does not cause an error</li>
1514 <h1>Roles as Interfaces</h1>
1517 <li>Roles can <code>require</code> methods of their consumers</li>
1518 <li>Compile-time checks</li>
1519 <li>Method must exist when the role is consumed</li>
1524 <h1>The Attribute Gotcha</h1>
1526 <pre><code>package HasSize;
1529 <span class="current incremental">requires 'size';</span>
1534 <span class="incremental">with 'HasSize';
1536 has size => ( is => 'ro' );</span></code></pre>
1540 <h1>The Attribute Gotcha Workaround</h1>
1542 <pre><code>package HasSize;
1550 has size => ( is => 'ro' );
1552 with 'HasSize';</code></pre>
1556 <h1>Compile-time Is a Lie</h1>
1559 <li>Really, it's <em>package load</em> time</li>
1560 <li>That's run-time, but before the "real" run-time</li>
1561 <li>Moose does not rewire Perl, it's just sugar!</li>
1562 <li>(but <code>MooseX::Declare</code> <em>does</em> rewire Perl)</li>
1567 <h1>Enforcing Roles</h1>
1569 <pre><code>package Comparison;
1572 has [ 'left', 'right' ] => (
1574 <span class="highlight">does => 'Comparable',</span>
1579 <li>A sneak peek at type constraints</li>
1585 <h1>Roles Can Be Applied to Objects</h1>
1587 <pre><code>use Moose::Util qw( apply_all_roles );
1589 my $fragile_person = Person->new( ... );
1590 apply_all_roles( $fragile_person,
1591 'IsFragile' );</code></pre>
1594 <li>Does not change the <code>Person</code> class</li>
1595 <li>Works with non-Moose classes, great for monkey-patching!</li>
1600 <h1>Roles Are Dirty Too</h1>
1603 <li>Once again, clean up those Moose droppings</li>
1606 <pre><code>package Comparable;
1611 <span class="highlight">no Moose::Role;</span></code></pre>
1614 <li>But roles cannot be made immutable</li>
1619 <h1>The Zen of Roles</h1>
1622 <li>Roles represent discrete units of ...
1629 <li>Roles are shareable between unrelated classes</li>
1630 <li>Roles are what a class <em>does</em>, not what it <em>is</em></li>
1631 <li>Roles <em>add</em> functionality, inheritance <em>specializes</em></li>
1636 <h1>Abstract Examples</h1>
1639 <li>Human <em>@ISA</em> Animal</li>
1640 <li>Human <em>does</em> Toolmaker (as <em>does</em> Chimpanzee)</li>
1641 <li>Car <em>@ISA</em> Vehicle</li>
1642 <li>Car <em>does</em> HasEngine</li>
1647 <h1>Real Examples</h1>
1650 <li>Objects representing SQL database components and queries
1652 <li>Schema, Table, Column, ColumnAlias</li>
1653 <li>Select, Insert, Update, Delete</li>
1660 <h1>Real Examples</h1>
1663 <li>Column and ColumnAlias both <em>do</em> ColumnLike</li>
1664 <li>ColumnLike things can be used in certain parts of queries</li>
1665 <li>All queries <em>do</em> HasWhereClause</li>
1666 <li>Select <em>does</em> Comparable and Selectable (for subselects)</li>
1667 <li>A where clause requires its components to <em>do</em> Comparable</li>
1672 <h1>Roles Summary</h1>
1675 <li>Roles can define an interface with <code>requires</code></li>
1676 <li>Roles can have state (attributes) and behavior (methods)</li>
1677 <li>Roles can mix interface, state, & behavior</li>
1678 <li>Roles are composed (flattened) into classes</li>
1679 <li>Roles can do other roles</li>
1680 <li>Roles can be used as a type in APIs (must do Comparable)</li>
1692 # perl bin/prove -lv t/02-roles.t
1694 Iterate til this passes all its tests</pre>
1697 <div class="slide fake-slide0">
1698 <h1>Part 3: Basic Attributes</h1>
1702 <h1>Attributes Are Huge</h1>
1705 <li>Moose's biggest feature</li>
1706 <li>The target of <em>many</em> MooseX modules</li>
1711 <h1>Quick Review</h1>
1714 <li>Declared with <code>has</code></li>
1715 <li>Read-only or read-write</li>
1718 <pre><code>package Shirt;
1721 has 'color' => ( is => 'ro' );
1722 has 'is_ripped' => ( is => 'rw' );</code></pre>
1726 <h1>Required-ness</h1>
1729 <li>Required means "must be passed to the constructor"</li>
1730 <li>But can be <code>undef</code></li>
1735 <h1>Required-ness</h1>
1737 <pre><code>package Person;
1740 has first_name => (
1742 <span class="current incremental">required => 1,</span>
1745 <span class="incremental">Person->new( first_name => undef ); # ok
1746 Person->new(); # kaboom</span></code></pre>
1750 <h1>Default and Builder</h1>
1753 <li>Attributes can have defaults</li>
1754 <li>Simple non-reference scalars (number, string)</li>
1755 <li>Subroutine reference</li>
1756 <li>A builder method</li>
1764 <li>Can be a non-reference scalar (including <code>undef</code>)</li>
1767 <pre><code>package Person;
1772 default => 'Spire FCU',
1780 <li>Can be a subroutine reference</li>
1783 <pre><code>package Person;
1790 name => 'Spire FCU' ) },
1795 <h1>Subroutine Reference Default</h1>
1798 <li>Called as a method on the object</li>
1799 <li>Called anew for each object</li>
1804 <h1>Why No Other Reference Types?</h1>
1806 <pre><code>package Person;
1811 <span class="wrong">default => Bank->new(
1812 name => 'Spire FCU' ),</span>
1816 <li>Now <strong>every</strong> person shares the <strong>same</strong> Bank object!</li>
1821 <h1>Defaulting to an Empty Reference</h1>
1823 <pre><code>package Person;
1826 has packages => (
1828 default => <span class="highlight">sub { [] }</span>,
1833 <h1>What if I Want to Share?</h1>
1835 <pre><code>package Person;
1838 my $highlander_bank =
1840 name => 'Clan MacLeod Trust' );
1844 default => sub { $highlander_bank },
1852 <li>A method <em>name</em></li>
1853 <li>When called, this method returns the default value</li>
1860 <pre><code>package Person;
1865 builder => '_build_bank',
1870 return Bank->new(
1871 name => 'Spire FCU' );
1876 <h1>Default vs Builder</h1>
1879 <li>Use default for simple scalars</li>
1880 <li>Use default to return empty references</li>
1881 <li>Use default for <em>very</em> trivial subroutine references</li>
1882 <li>Use builder for everything else</li>
1887 <h1>Builder Bonuses</h1>
1890 <li>Can be overridden and method modified, because it's called by <em>name</em></li>
1891 <li>Roles can require a builder</li>
1896 <h1>Role Requires Builder</h1>
1898 <pre><code>package HasBank;
1901 requires '_build_bank';
1905 builder => '_build_bank',
1910 <h1>Lazy, Good for Nothin' Attributes</h1>
1913 <li>Normally, defaults are generated during object construction</li>
1914 <li>This can be expensive</li>
1915 <li>We want to default to <code>$self->size * 2</code>, but attribute initialization order is unpredictable</li>
1916 <li>Use lazy attributes!</li>
1921 <h1>The Power of Dynamic Defaults</h1>
1923 <pre><code>package Person;
1926 has shoe_size => (
1933 <h1>The Power of Dynamic Defaults</h1>
1935 <pre><code>has shoes => (
1937 <span class="highlight">lazy => 1,</span>
1938 builder => '_build_shoes',
1944 return Shoes->new(
1945 size => <span class="highlight">$self->shoe_size</span> );
1950 <h1>Lazy is Good</h1>
1953 <li>Lazy defaults are executed when the attribute is read</li>
1954 <li>Can see other object attributes</li>
1955 <li>Still need to watch out for circular laziness</li>
1960 <h1>Clearer and Predicate</h1>
1963 <li>Attributes can have a value, including <code>undef</code>, or not</li>
1964 <li>Can clear the value with a clearer method</li>
1965 <li>Can check for the existence of a value with a predicate method</li>
1966 <li>By default, these methods are not created</li>
1971 <h1>Clearer and Predicate</h1>
1973 <pre><code>package Person;
1979 builder => '_build_account',
1980 <span class="highlight">clearer => '_clear_account',
1981 predicate => 'has_account',</span>
1986 <h1>Clearer and Lazy Defaults</h1>
1989 <li>Lazy defaults are good for computed attributes</li>
1990 <li>Clear the attribute when the source data changes</li>
1991 <li>Recalculated at next access</li>
1996 <h1>Renaming constructor arguments</h1>
1999 <li>By default, constructor names = attribute names</li>
2000 <li>Use <code>init_arg</code> to change this</li>
2001 <li>Set <code>init_arg => undef</code> to make it unconstructable</li>
2006 <h1>Some <code>init_arg</code> examples</h1>
2008 <pre><code>package Person;
2011 has shoe_size => (
2013 <span class="highlight">init_arg => 'foot_size',</span>
2016 Person->new( <span class="wrong">shoe_size => 13</span> );
2019 Person->new( <span class="right">foot_size => 13</span> );
2020 print $person->shoe_size;</code></pre>
2024 <h1>Some <code>init_arg</code> examples</h1>
2026 <pre><code>package Person;
2031 <span class="highlight">init_arg => undef,</span>
2034 Person->new( <span class="wrong">shoes => Shoes->new</span> );</code></pre>
2038 <h1>Why Set <code>init_arg => undef</code>?</h1>
2041 <li>Use this with a lazy default for attributes-as-cache</li>
2042 <li>Compute the value as needed</li>
2043 <li>Ensure that it is always generated correctly (not set by constructor)</li>
2044 <li>Use triggers or method modifiers (coming soon) to clear the value</li>
2049 <h1>Attribute Inheritance</h1>
2052 <li>By default, subclasses inherit attribute as-is</li>
2053 <li>Can change some attribute parameters in subclasses
2059 <li>others we've not yet covered</li>
2066 <h1>Attribute Inheritance Example</h1>
2068 <pre><code>package Employee;
2073 has '<span class="highlight">+first_name</span>' => (
2074 default => 'Joe',
2079 <h1>Attribute Inheritance Warning</h1>
2082 <li>An attribute is a contract about a class's API</li>
2083 <li>Don't break that contract in a subclass</li>
2084 <li>Especially important in the context of types</li>
2089 <h1>Changing Accessor Names</h1>
2091 <pre><code>package Person;
2094 has first_name => (
2095 <span class="highlight">accessor</span> => 'first_name',
2099 <li>The long-hand version of <code>is => 'rw'</code></li>
2104 <h1>Changing Accessor Names</h1>
2106 <pre><code>package Person;
2109 has first_name => (
2110 <span class="highlight">reader</span> => 'first_name',
2111 <span class="highlight">writer</span> => undef,
2115 <li>The long-hand version of <code>is => 'ro'</code></li>
2121 <h1>Changing Accessor Names</h1>
2123 <pre><code>package Person;
2126 has first_name => (
2127 <span class="highlight">reader</span> => 'get_first_name',
2128 <span class="highlight">writer</span> => 'set_first_name',
2133 <h1>Changing Accessor Names</h1>
2135 <pre><code>package Person;
2138 has first_name => (
2139 <span class="highlight">is</span> => 'rw',
2140 <span class="highlight">writer</span> => '_first_name',
2144 <li>Can also mix-and-match <code>is</code> and explicit names</li>
2149 <h1>ETOOMUCHTYPING</h1>
2152 <li><code>MooseX::FollowPBP</code><br /><code>get_foo</code> and <code>set_foo</code></li>
2153 <li><code>MooseX::SemiAffordanceAccessor</code><br /><code>foo</code> and <code>set_foo</code></li>
2158 <h1>ETOOMUCHTYPING</h1>
2160 <pre><code>package Person;
2162 <span class="highlight">use MooseX::SemiAffordanceAccessor;</span>
2164 has first_name => (
2169 <li>Creates <code>first_name</code> and <code>set_first_name</code></li>
2174 <h1>Basic Attributes Summary</h1>
2177 <li>Attributes can be <code>required</code></li>
2178 <li>Attributes can have a <code>default</code> or <code>builder</code></li>
2179 <li>Attributes with a default or builder can be <code>lazy</code></li>
2180 <li>Attributes can have a <code>clearer</code> and/or <code>predicate</code></li>
2185 <h1>Basic Attributes Summary</h1>
2188 <li>An attribute's constructor name can be changed with <code>init_arg</code></li>
2189 <li>A subclass can alter its parents' attributes</li>
2190 <li>Attribute accessor names can be changed</li>
2202 # perl bin/prove -lv \
2203 t/03-basic-attributes.t
2205 Iterate til this passes all its tests</pre>
2208 <div class="slide fake-slide0">
2209 <h1>Part 4: Method Modifiers</h1>
2213 <h1>What is a Method Modifier</h1>
2216 <li>Apply to an existing method</li>
2217 <li>... that comes from a parent class, the current class, or a role</li>
2218 <li>Roles can provide modifiers that are applied at composition time</li>
2223 <h1>What Are Method Modifiers For?</h1>
2226 <li>"Inject" behavior</li>
2227 <li>Add behavior to generated methods (accessors, delegations)</li>
2228 <li>Added from a role, can modify existing behavior</li>
2233 <h1>Before and After</h1>
2236 <li>Simplest modifiers - <code>before</code> and <code>after</code></li>
2237 <li>Guess when they run!</li>
2242 <h1>Uses for <code>before</code></h1>
2245 <li>As a pre-call check</li>
2248 <pre><code>package Person;
2251 before work => sub {
2253 die 'I have no job!'
2254 unless $self->has_title;
2259 <h1>Uses for <code>before</code></h1>
2262 <li>Logging/Debugging</li>
2265 <pre><code>package Person;
2268 before work => sub {
2270 return unless $DEBUG;
2272 warn "Called work on ",
2273 $self->full_name,
2274 "with the arguments: [@_]\n";
2279 <h1>Uses for <code>after</code></h1>
2282 <li>Also works for logging/debugging</li>
2283 <li>Post-X side-effects (recording audit info)</li>
2286 <pre><code>package Person;
2289 after work => sub {
2291 $self->work_count(
2292 $self->work_count + 1 );
2300 <li>Modifiers are useful for adding behavior to generated methods</li>
2305 <h1>More Modifier Examples</h1>
2307 <pre><code>has password => (
2309 clearer => 'clear_password',
2311 has hashed_password => (
2313 builder => '_build_hashed_password',
2314 clearer => '_clear_hashed_password',
2316 after clear_password => sub {
2318 $self->_clear_hashed_password;
2323 <h1><code>before</code> and <code>after</code> Limitations</h1>
2326 <li>Cannot alter method parameters</li>
2327 <li>Cannot alter return value</li>
2328 <li>But <strong>can</strong> throw an exception</li>
2333 <h1>The <code>around</code> Modifier</h1>
2336 <li>The big gun</li>
2337 <li>Can alter parameters <strong>and/or</strong> return values</li>
2338 <li>Can skip calling the wrapped method entirely</li>
2343 <h1>The power of <code>around</code></h1>
2345 <pre><code>around insert => sub {
2349 $self->_validate_insert(@_);
2353 $self->_munge_insert(@_) );
2355 $new_user->_assign_uri;
2361 <h1>Modifier Order</h1>
2364 <li>Before runs in order from last to first</li>
2365 <li>After runs in order from first to last</li>
2366 <li>Around runs in order from last to first</li>
2371 <h1>Modifier Order Illustrated</h1>
2374 <span class="current incremental">before 2
2376 <span class="incremental">around 2
2378 <span class="incremental">wrapped method</span>
2379 <span class="incremental">around 1
2381 <span class="incremental">after 1
2387 <h1>Modifiers in Roles</h1>
2390 <li>Roles can use these modifiers</li>
2391 <li>Very powerful!</li>
2396 <h1>Modifiers in Roles</h1>
2398 <pre><code>package IsUnreliable;
2401 <span class="highlight">requires 'run';
2403 around run</span> => sub {
2407 return if rand(1) < 0.5;
2409 return $self->$orig(@_);
2414 <h1>Augment and Inner</h1>
2417 <li>Inverted <code>super</code></li>
2418 <li>From least- to most-specific</li>
2419 <li>Like Mason's autohandler feature</li>
2420 <li>Grandparent to parent to child</li>
2421 <li>Not allowed in roles</li>
2426 <h1>Augment and Inner</h1>
2428 <pre class="medium"><code>package Document;
2430 sub xml { '<doc>' . <span class="highlight">inner()</span> . '</doc>' }
2434 <span class="highlight">augment xml</span> =>
2435 sub { my $self = shift;
2436 $self->title() . <span class="highlight">inner()</span> . $self->summary() };
2440 <span class="highlight">augment xml</span> =>
2441 sub { my $self = shift;
2442 $self->tps_xml() . <span class="highlight">inner()</span> };</code></pre>
2446 <h1>Augment and Inner</h1>
2449 <li>When we call <code>$tps->xml</code> ...
2451 <li><code>Document->xml</code></li>
2452 <li><code>Report->xml</code></li>
2453 <li><code>TPSReport->xml</code></li>
2460 <h1>Augment and Inner Usage</h1>
2463 <li>Call <code>inner()</code> to "fill in the blank"</li>
2464 <li>Requires designing for subclassing</li>
2465 <li>Call <code>inner()</code> in the terminal class, just in case</li>
2470 <h1>Method Modifiers Summary</h1>
2473 <li>Use <code>before</code> and <code>after</code> for ...
2476 <li>pre- or post-validation</li>
2477 <li>to add behavior to generated methods</li>
2480 <li>These two modifiers cannot change parameters or return values</li>
2485 <h1>Method Modifiers Summary</h1>
2488 <li>Use <code>around</code> to ...
2490 <li>alter parameters passed to the original method</li>
2491 <li>alter the return value of the original method</li>
2492 <li>not call the original method at all (or call a <em>different</em> method)</li>
2499 <h1>Method Modifiers Summary</h1>
2502 <li>When using modifiers in a role, require the modified method</li>
2503 <li>Use <code>augment</code> and <code>inner</code> to invert the normal subclassing flow ...
2505 <li>Least- to most-specific (parents to children)</li>
2506 <li>Build in "insertability" (stick more stuff in the "middle")</li>
2509 <li>Always call <code>inner</code> in the most specific subclass to allow for future extension</li>
2521 # perl bin/prove -lv \
2522 t/04-method-modifiers.t
2524 Iterate til this passes all its tests</pre>
2527 <div class="slide fake-slide0">
2528 <h1>Part 5: Types</h1>
2532 <h1>A Type System for Perl</h1>
2535 <li>Sort of ...</li>
2536 <li><em>Variables</em> are not typed</li>
2537 <li>Attributes can have types</li>
2538 <li>MooseX modules let you define method signatures</li>
2543 <h1>Components of a Moose Type</h1>
2546 <li>A type is a name and a constraint</li>
2547 <li>Types have a hierarchy</li>
2548 <li>Constraints are cumulative from parents</li>
2549 <li>Types can have associated coercions</li>
2554 <h1>Built-in Type Hierarchy</h1>
2573 <h1>Built-in Type Hierarchy</h1>
2595 <pre><code>1</code></pre>
2604 <li>Like Perl's <code>if ($foo)</code></li>
2609 <h1>Value (and subtypes)</h1>
2612 <li><code>Value</code> is true when <code>! ref $thing</code></li>
2613 <li><code>Value</code> and <code>Str</code> are effectively the same, but <code>Str</code> is more expressive</li>
2614 <li><code>Num</code> is true when a <code>$scalar</code> looks like a number</li>
2615 <li>An overloaded object which numifies does not pass the <code>Num</code> constraint!</li>
2616 <li>Perl 5's overloading is hopelessly broken</li>
2621 <h1>ClassName and RoleName</h1>
2624 <li>A string with a package name</li>
2625 <li>The package <strong>must already be loaded</strong></li>
2630 <h1>Parameterizable Types</h1>
2633 <li>What does <code>ArrayRef[`a]</code> mean?</li>
2634 <li><code>s/`a/Int/</code> (or <code>Str</code> or ...)</li>
2635 <li>When you use it you can write ...
2637 <li><code>ArrayRef</code> (== <code>ArrayRef[Item]</code>)</li>
2638 <li><code>ArrayRef[Str]</code></li>
2639 <li><code>ArrayRef[MyTypeName]</code></li>
2640 <li><code>ArrayRef[HashRef[Maybe[Int]]]</code></li>
2650 <li>Maybe means either the named type or <code>undef</code></li>
2651 <li><code>Maybe[Int]</code> accepts integers or <code>undef</code></li>
2659 <li>This or that (or that or ...)</li>
2660 <li><code>Int | ArrayRef[Int]</code></li>
2661 <li>But use a coercion instead when possible</li>
2662 <li>Or use a <code>role_type</code>, <code>duck_type</code>, or anything not a union</li>
2663 <li>A union is often a code smell</li>
2668 <h1>Making Your Own Types</h1>
2670 <pre><code>use Moose::Util::TypeConstraints;
2672 <span class="incremental current">subtype 'PositiveInt',</span>
2673 <span class="incremental">as 'Int',</span>
2674 <span class="incremental">where { $_ > 0 },</span>
2675 <span class="incremental">message
2676 { "The value you provided ($_)"
2677 . " was not a positive int." };</span>
2681 <span class="incremental">isa => 'PositiveInt',</span>
2686 <h1>Automatic Types</h1>
2689 <li>Moose creates a type for every Moose class and role</li>
2690 <li>Unknown names are assumed to be classes</li>
2695 <h1>Automatic Types</h1>
2697 <pre><code>package Employee;
2702 <span class="highlight">isa => 'Employee',</span>
2705 has start_date => (
2707 <span class="highlight">isa => 'DateTime',</span>
2712 <h1>Subtype Shortcuts - <code>class_type</code></h1>
2714 <pre><code>use Moose::Util::TypeConstraints;
2715 class_type 'DateTime';</code></pre>
2719 <pre><code>subtype 'DateTime',
2721 where { $_->isa('DateTime') },
2722 message { ... };</code></pre>
2726 <h1>Subtype Shortcuts - <code>role_type</code></h1>
2728 <pre><code>use Moose::Util::TypeConstraints;
2729 role_type 'Printable';</coe></pre>
2733 <pre><code>subtype 'Printable',
2736 { Moose::Util::does_role(
2737 $_, 'Printable' ) },
2738 message { ... };</code></pre>
2742 <h1>Subtype Shortcuts - <code>duck_type</code></h1>
2744 <pre><code>use Moose::Util::TypeConstraints;
2745 duck_type Car => qw( run break_down );</code></pre>
2749 <pre><code>subtype 'Car',
2751 where { all { $_->can($_) }
2752 qw( run break_down ) },
2753 message { ... };</code></pre>
2757 <h1>Subtype Shortcuts - <code>enum</code></h1>
2759 <pre><code>use Moose::Util::TypeConstraints;
2760 enum Color => qw( red blue green );</code></pre>
2764 <pre><code>my %ok = map { $_ => 1 }
2765 qw( red blue green );
2770 message { ... };</code></pre>
2774 <h1>Anonymous Subtypes</h1>
2776 <pre><code>package Person;
2778 <span class="highlight">my $posint =
2779 subtype as 'Int', where { $_ > 0 };</span>
2783 <span class="highlight">isa => $posint,</span>
2787 <li>Shortcuts have anonymous forms as well</li>
2794 <pre><code>use Moose::Util::TypeConstraints;
2798 where { ! /[a-z]/ };</code></pre>
2804 <pre><code><span class="incremental current">coerce 'UCStr',</span>
2805 <span class="incremental">from 'Str',</span>
2806 <span class="incremental">via { uc };</span>
2808 has shouty_name => (
2811 <span class="incremental">coerce => 1,</span>
2816 <h1>Coercion Examples</h1>
2818 <pre><code>subtype 'My::DateTime',
2819 as class_type 'DateTime';
2821 coerce 'My::DateTime',
2823 via { DateTime->new( %{$_} ) };
2825 coerce 'My::DateTime',
2827 via { DateTime->from_epoch(
2828 epoch => $_ ) };</code></pre>
2831 <li>Use coercion to inflate a value</li>
2836 <h1>Coercion Examples</h1>
2838 <pre><code>coerce 'ArrayRef[Int]',
2840 via { [ $_ ] };</code></pre>
2843 <li>Instead of union - <code style="white-space: nowrap">Int | ArrayRef[Int]</code></li>
2848 <h1>Using Types with Attributes</h1>
2850 <pre><code>package Person;
2854 <span class="highlight">isa => 'Num',</span>
2857 has favorite_numbers => (
2859 <span class="highlight">isa => 'ArrayRef[Int]',
2860 coerce => 1,</span>
2865 <h1>More Droppings</h1>
2868 <li><code>Moose::Util::TypeConstraints</code> also needs cleanup</li>
2871 <pre><code>package Person;
2874 use Moose::Util::TypeConstraints;
2879 <span class="highlight">no Moose::Util::TypeConstraints;</span></code></pre>
2883 <h1>Questions So Far?</h1>
2890 # perl bin/prove -lv t/05-types.t
2892 Iterate til this passes all its tests</pre>
2896 <h1>Typed Methods (Low-tech)</h1>
2898 <pre class="medium"><code>package Person;
2899 <span class="highlight">use MooseX::Params::Validate qw( validated_list );</span>
2903 <span class="highlight">my ( $tasks, $can_rest ) =
2907 { isa => 'ArrayRef[Task]',
2918 <h1>Typed Methods (High-tech)</h1>
2920 <pre class="medium"><code>package Person;
2922 <span class="highlight">use MooseX::Method::Signatures;</span>
2924 <span class="highlight">method work ( ArrayRef[Task] :$tasks,
2925 Bool :$can_rest = 0 )</span> {
2933 <h1>Digression: The Type Registry</h1>
2936 <li>Types are actually <code>Moose::Meta::TypeConstraints</code> <em>objects</em></li>
2937 <li>Stored in an interpreter-global registry mapping names to objects</li>
2945 <li>Coercions are attached to type objects</li>
2946 <li>Therefore also global</li>
2947 <li>Name conflicts between modules!</li>
2948 <li>Coercion conflicts between modules!</li>
2953 <h1>Namespace Fix</h1>
2956 <li>Use some sort of pseudo-namespacing scheme</li>
2957 <li>Never coerce directly to a class name, or <em>to</em> built-in types</li>
2962 <h1>Namespace Fix</h1>
2964 <pre><code>use Moose::Util::TypeConstraints;
2965 subtype <span class="highlight">'MyApp::Type::DateTime',</span>
2968 <span class="highlight">coerce 'MyApp::Type::DateTime',</span>
2970 via { DateTime->new( %{$_} ) }
2972 has creation_date => (
2974 <span class="highlight">isa => 'MyApp::Type::DateTime',</span>
2980 <h1>Namespace Fix</h1>
2982 <pre><code>subtype 'MyApp::Type::ArrayOfInt',
2985 coerce 'MyApp::Type::ArrayOfInt',
2987 via { [ $_ ] };</code></pre>
2991 <h1>Namespace Fix Pros and Cons</h1>
2994 <li><span class="right">Relatively simple</span></li>
2995 <li><span class="right">Already built into Moose</span></li>
2996 <li><span class="wrong">Conflates type and module namespaces</span></li>
2997 <li><span class="wrong">Type names are strings, so typos are easy to make and may be hard to find</span></li>
3002 <h1>MooseX::Types</h1>
3004 <pre><code>package MyApp::Types;
3007 <span class="highlight">-declare => [ qw( ArrayOfInt ) ]</span>;
3008 use MooseX::Types::Moose
3011 subtype <span class="highlight">ArrayOfInt</span>,
3014 coerce <span class="highlight">ArrayOfInt</span>
3016 via { [ $_ ] };</code></pre>
3020 <h1>MooseX::Types</h1>
3022 <pre><code>package MyApp::Account;
3024 use MyApp::Types qw( ArrayOfInt );
3026 has transaction_history => (
3028 isa => ArrayOfInt,
3033 <h1>MooseX::Types</h1>
3036 <li>Type names are exported functions, catches typos early</li>
3037 <li>Types must be pre-declared</li>
3038 <li>Types are stored with namespaces internally, but you use short names</li>
3039 <li>Import existing Moose types as functions from <code>MooseX::Types::Moose</code></li>
3040 <li>Still need string names for things like <code>ArrayRef['Email::Address']</code></li>
3045 <h1>MooseX::Types Pros and Cons</h1>
3048 <li><span class="right">Catches typos at compile time</span></li>
3049 <li><span class="right">Automatic namespacing</span></li>
3050 <li><span class="wrong">One more thing to install and learn</span></li>
3051 <li><span class="wrong">Every name is typed twice (declared and then defined)</span></li>
3052 <li><span class="wrong">Still stuck with strings when referring to class or role names</span></li>
3053 <li><span class="wrong">Coercion gotcha from earlier still applies to types exported from <code>MooseX::Types::Moose</code></span></li>
3058 <h1>Recommendation</h1>
3061 <li>Use <code>MooseX::Types</code></li>
3062 <li>Compile time error catching and automatic namespacing are huge wins</li>
3063 <li>Docs from <code>Moose::Util::TypeConstraints</code> are 98% compatible with <code>MooseX::Types</code> anyway</li>
3064 <li>A function exported by a type library works wherever a type name would</li>
3072 <div class="slide fake-slide0">
3073 <h1>Part 6: Advanced Attributes</h1>
3077 <h1>Weak References</h1>
3080 <li>A weak reference lets you avoid circular references</li>
3081 <li>Weak references do not increase the reference count</li>
3086 <h1>Circular Reference Illustrated</h1>
3088 <pre><code>my $foo = {};
3089 my $bar = { foo => $foo };
3090 $foo->{bar} = $bar;</code></pre>
3093 <li>Neither <code>$foo</code> nor <code>$bar</code> go out of scope<br />
3094 (until the program exits)</li>
3099 <h1>Weakening Circular References</h1>
3101 <pre><code>use Scalar::Util qw( weaken );
3104 my $bar = { foo => $foo };
3105 $foo->{bar} = $bar;
3106 weaken $foo->{bar}</code></pre>
3109 <li>When <code>$bar</code> goes out of scope, <code>$foo->{bar}</code> becomes <code>undef</code></li>
3114 <h1>Circular References in Attributes</h1>
3116 <pre><code>package Person;
3119 has name => ( is => 'ro' );
3120 has friend => ( is => 'rw' );
3122 my $alice = Person->new( name => 'Alice' );
3123 my $bob = Person->new( name => 'Bob' );
3124 $bob->friend($alice);
3125 $alice->friend($bob);</code></pre>
3131 <pre><code>package Person;
3134 has name => ( is => 'ro' );
3135 has friend => ( is => 'rw',
3136 <span class="highlight">weak_ref => 1</span> );
3138 my $alice = Person->new( name => 'Alice' );
3139 my $bob = Person->new( name => 'Bob' );
3140 $bob->friend($alice);
3141 $alice->friend($bob);</code></pre>
3145 <h1>Under the Hood</h1>
3148 <li>A <code>weak_ref</code> attribute calls <code>weaken</code> ...
3150 <li>during object construction</li>
3151 <li>when the attribute is set via a writer</li>
3161 <li>A code reference run after an attribute is <em>set</em></li>
3162 <li>Like an <code>after</code> modifier, but makes intentions clearer</li>
3165 <h2 class="wrong">Gross</h2>
3167 <pre><code>after salary_level => {
3169 <span class="highlight">return unless @_;</span>
3170 $self->clear_salary;
3175 <h1>Use a Trigger Instead</h1>
3177 <h2 class="right">Cleaner</h2>
3179 <pre><code>has salary_level => (
3182 sub { $_[0]->clear_salary },
3187 <h1>Trigger Arguments</h1>
3190 <li><code>$self</code></li>
3191 <li><code>$new_value</code></li>
3192 <li><code>$old_value</code> - if one exists</li>
3200 <li>Attributes can be objects</li>
3201 <li>Delegation transparently calls methods on those objects</li>
3206 <h1>Delegation Examples</h1>
3208 <pre><code>package Person;
3213 <span class="highlight">handles => [ 'inhale', 'exhale' ],</span>
3217 <li>Creates <code>$person->inhale</code> and <code>->exhale</code> methods</li>
3218 <li>Internally calls <code>$person->lungs->inhale</code></li>
3223 <h1>Why Delegation?</h1>
3226 <li>Reduce the number of classes exposed</li>
3227 <li>Re-arrange class internals -<br />
3228 turn a method into an attribute with delegation</li>
3229 <li>Provide convenenience methods</li>
3234 <h1>Moose's <code>handles</code> Parameter</h1>
3237 <li>Accepts many arguments ...
3239 <li>Array reference - list of methods to delegate as-is</li>
3240 <li>Hash reference - map of method names</li>
3241 <li>Regex - delegates all matching methods</li>
3242 <li>Role name - delegates all methods in the role</li>
3243 <li>Sub reference - does something complicated ;)</li>
3250 <h1>Array Reference</h1>
3253 <li>1-to-1 mapping</li>
3254 <li>Takes each method name and creates a simple delegation from the delegating class to the delegatee attribute</li>
3259 <h1>Hash Reference</h1>
3262 <li>Mapping of names in the delegating class to the delegatee class</li>
3265 <pre><code>package Person;
3269 isa => 'BankAccount',
3270 <span class="highlight">handles => {
3271 receive_money => 'deposit',
3272 give_money => 'withdraw',
3278 <h1>Hash Reference Detailed</h1>
3280 <pre><code> handles => {
3281 receive_money => 'deposit',
3282 give_money => 'withdraw',
3286 <li><code>$person->receive_money</code> = <code>$person->account->deposit</code></li>
3287 <li><code>$person->give_money</code> = <code>$person->account->withdraw</code></li>
3294 <pre><code>package Person;
3300 handles => qr/.*/,
3304 <li>Creates a delegation for every method in the Name class</li>
3305 <li>Excludes <code>meta</code> and methods inherited from <code>Moose::Object</code></li>
3312 <pre><code>package Auditor;
3314 sub record_change { ... }
3315 sub change_history { ... }
3322 does => 'Auditor',
3323 <span class="highlight">handles => 'Auditor',</span>
3328 <h1>Role Name Detailed</h1>
3331 <li>Account gets delegate methods for each method in the <code>Auditor</code> role
3333 <li>record_history</li>
3334 <li>change_history</li>
3341 <h1>Native Delegation</h1>
3344 <li>Delegate to <em>unblessed</em> Perl types</li>
3345 <li>Scalar, array or hash ref, etc</li>
3346 <li>Treat Perl types as objects</li>
3347 <li>Still uses <code>handles</code></li>
3348 <li>Pretend that native Perl types have methods</li>
3353 <h1>Native Delegation - Array(Ref)</h1>
3356 <li>Methods include:
3358 <li><code>push</code></li>
3359 <li><code>shift</code></li>
3360 <li><code>elements</code> - returns all elements</li>
3361 <li><code>count</code></li>
3362 <li><code>is_empty</code></li>
3363 <li>quite a few more</li>
3370 <h1>Native Delegation - Array(Ref)</h1>
3372 <pre><code>package Person;
3374 has _favorite_numbers => (
3375 traits => [ 'Array' ],
3377 isa => 'ArrayRef[Int]',
3378 default => sub { [] },
3379 init_arg => undef,
3380 <span class="highlight">handles =>
3381 { favorite_numbers => 'elements',
3382 add_favorite_number => 'push',
3388 <h1>Native Delegation - Array(Ref)</h1>
3390 <pre><code>my $person = Person->new();
3392 $person->add_favorite_number(7);
3393 $person->add_favorite_number(42);
3396 for $person->favorite_numbers;
3403 <h1>Native Delegation</h1>
3406 <li>Native types are ...
3408 <li>Number - <code>add</code>, <code>mul</code>, ...</li>
3409 <li>String - <code>append</code>, <code>chop</code>, ...</li>
3410 <li>Counter - <code>inc</code>, <code>dec</code>, ...</li>
3411 <li>Bool - <code>set</code>, <code>toggle</code>, ...</li>
3412 <li>Hash - <code>get</code>, <code>set</code>, ...</li>
3413 <li>Array - already saw it</li>
3414 <li>Code - <code>execute</code> and <code>execute_method</code></li>
3421 <h1>Curried Delegation</h1>
3424 <li>A delegation with some preset arguments</li>
3425 <li>Works with object or Native delegation</li>
3430 <h1>Curried Delegation</h1>
3432 <pre><code>package Person;
3436 isa => 'BankAccount',
3439 <span class="highlight">[ 'deposit', 100 ]</span>
3441 <span class="highlight">[ 'withdraw', 100 ]</span>
3447 <h1>Curried Delegation</h1>
3449 <pre><code>$person->receive_100;
3451 $person->account->deposit(100);</code></pre>
3455 <h1>Traits and Metaclasses</h1>
3458 <li>The ultimate in customization</li>
3459 <li>Per attribute metaclasses</li>
3460 <li>Per attribute roles applied to the attribute metaclass</li>
3461 <li>Change the meta-level behavior</li>
3466 <h1>Traits and Metaclasses</h1>
3469 <li>The default metaclass is <code>Moose::Meta::Attribute</code></li>
3470 <li>Controls accessor generation, defaults, delegation, etc.</li>
3471 <li>Adding a role to this metaclass (or replacing it) allows for infinite customization</li>
3476 <h1>Traits and Metaclasses</h1>
3479 <li>Can add/alter/remove an attribute parameter (from <code>has</code>)</li>
3480 <li>Can change behavior of created attribute</li>
3485 <h1>Simple Trait Example</h1>
3487 <pre><code>package Person;
3489 use MooseX::LabeledAttributes;
3492 <span class="highlight">traits => [ 'Labeled' ],</span>
3495 <span class="highlight">label => 'Social Security Number',</span>
3497 print <span class="highlight">Person->meta
3498 ->get_attribute('ssn')->label;</span></code></pre>
3502 <h1>Simple Metaclass Example</h1>
3504 <pre><code>package Person;
3506 use MooseX::LabeledAttributes;
3509 <span class="highlight">metaclass =>
3510 'MooseX::Meta::Attribute::Labeled',</span>
3513 <span class="highlight">label => 'Social Security Number',</span>
3515 print <span class="highlight">Person->meta
3516 ->get_attribute('ssn')->label;</span></code></pre>
3520 <h1>Traits vs Metaclass</h1>
3523 <li>Can apply any mix of traits to an attribute</li>
3524 <li>But just one metaclass</li>
3525 <li>Traits (aka roles) can cooperate</li>
3526 <li>Metaclasses require you to pick just one</li>
3531 <h1>Advanced Attributes Summary</h1>
3534 <li>Use <code>weak_ref</code> to avoid circular references</li>
3535 <li>Use trigger to do an action post-attribute write</li>
3536 <li>Use delegations to hide "internal" objects</li>
3537 <li>Use native delegations to treat Perl types as objects</li>
3538 <li>Traits and metaclasses let you extend Moose's core attribute features</li>
3546 # perl bin/prove -lv \
3547 t/06-advanced-attributes.t
3549 Iterate til this passes all its tests</pre>
3556 If there is time, keep going ...
3560 Otherwise, jump to slide 269 ...
3564 <div class="slide fake-slide0">
3565 <h1>Bonus: A Brief Tour of MooseX</h1>
3569 <h1>Notable MX Modules on CPAN</h1>
3572 <li><strong>Not comprehensive</strong></li>
3573 <li>177 MooseX distributions on CPAN as of 09/21/2010</li>
3574 <li>Some of them are crap</li>
3579 <h1>Already Mentioned Several</h1>
3582 <li><code>MooseX::NonMoose</code> - best solution for subclassing non-Moose parents</li>
3583 <li><code>MooseX::Declare</code> - <em>real</em> Perl 5 OO</li>
3584 <li><code>MooseX::FollowPBP</code> and <code>MooseX::SemiAffordanceAccessor</code></li>
3585 <li><code>MooseX::Params::Validate</code> and <code>MooseX::Method::Signatures</code></li>
3586 <li><code>MooseX::Types</code></li>
3591 <h1>MooseX::Declare</h1>
3593 <pre><code>use MooseX::Declare;
3594 use 5.10.0; # for say
3598 ( is => 'ro', isa => 'Str' );
3601 say $self->greeting;
3607 <h1>MooseX::Declare</h1>
3610 <li>Still experimental-ish, but seeing more and more use</li>
3611 <li><strong>Not</strong> a source filter!</li>
3612 <li>Hooks into the Perl parser rather than filtering all your code</li>
3613 <li>But not supported by <code>PPI</code>, <code>perltidy</code>, etc.</li> (yet?)
3618 <h1>MooseX::StrictConstructor</h1>
3621 <li>By default, unknown constructor arguments are ignored</li>
3622 <li>MX::StrictConstructor turns these into an error</li>
3627 <h1>MooseX::StrictConstructor</h1>
3629 <pre><code>package Person;
3632 <span class="highlight">use MooseX::StrictConstructor;</span>
3634 has name => ( is => 'ro' );
3637 ( na<span class="wrong">n</span>e => 'Ringo Shiina' ); # kaboom</code></pre>
3641 <h1>MooseX::Traits</h1>
3644 <li>Combines object construction and role application</li>
3645 <li>Makes it easy to create one-off customized objects</li>
3650 <h1>MooseX::Traits</h1>
3652 <pre><code>package MyApp::Thingy;
3655 <span class="highlight">with 'MooseX::Traits';</span>
3658 MyApp::Thingy-><span class="highlight">new_with_traits</span>
3659 ( <span class="highlight">traits => [ 'Foo', 'Bar' ],</span>
3660 size => 42 );</code></pre>
3664 <h1>MooseX::Getopt</h1>
3667 <li>Makes command-line interface programs easy!</li>
3668 <li>Construct an object from CLI arguments</li>
3673 <h1>MooseX::Getopt</h1>
3675 <pre><code>package App::CLI;
3678 <span class="highlight">with 'MooseX::Getopt';</span>
3681 ( is => 'ro', required => 1 );
3683 ( is => 'ro', isa => 'ArrayRef[Str]' );
3685 sub run { ... }</code></pre>
3689 <h1>MooseX::Getopt</h1>
3692 <li>Then call it like this:</li>
3695 <pre><code>#!/usr/bin/perl
3699 <span class="highlight">App::CLI->new_with_options()</span>->run();</code></pre>
3703 --filters compress \
3704 --filters sanitize</pre>
3708 <h1>MooseX::Clone</h1>
3710 <pre><code>package Person;
3713 <span class="highlight">with 'MooseX::Clone';</span>
3715 my $person = Person->new;
3716 my $clone = <span class="highlight">$person->clone;</span></code></pre>
3720 <h1>MooseX::NonMoose</h1>
3723 <li>Highly recommended for subclassing non-Moose parents</li>
3724 <li>Gets all the little annoying details right</li>
3729 <h1>MooseX::Role::Parameterized</h1>
3731 <pre><code>package HasCollection;
3732 <span class="current incremental">use MooseX::Role::Parameterized;</span>
3733 <span class="incremental">parameter type => ( isa => 'Str',
3734 default => 'Item' );</span>
3735 <span class="incremental">role {
3739 'ArrayRef[' . $p->type() . ']';
3740 has collection =>
3743 };</span></code></pre>
3747 <h1>MooseX::Role::Parameterized</h1>
3749 <pre><code>package Person;
3752 with HasCollection => { type => 'Int' };</code></pre>
3760 <h1>Moose-using Modules</h1>
3763 For further reading, a few modules which use Moose ...
3767 <li><a href="http://search.cpan.org/dist/Catalyst-Runtime">Catalyst</a></li>
3768 <li><a href="http://search.cpan.org/dist/CHI">CHI</a></li>
3769 <li><a href="http://search.cpan.org/dist/Devel-REPL">Devel::REPL</a></li>
3770 <li><a href="http://search.cpan.org/dist/Email-Sender">Email::Sender</a></li>
3771 <li><a href="http://search.cpan.org/dist/Fey">Fey</a></li>
3772 <li><a href="http://search.cpan.org/dist/Net-Twitter">Net::Twitter</a></li>
3777 <h1>More Information</h1>
3780 <li><a href="http://moose.perl.org/">http://moose.perl.org/</a></li>
3781 <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>
3782 <li><a href="irc://irc.perl.org/#moose">irc://irc.perl.org/#moose</a></li>
3783 <li>mailing list - <a href="mailto:moose@perl.org">moose@perl.org</a></li>
3784 <li>Slides and exercises are in Moose's git repo:
3786 <span style="font-size:80%; white-space: nowrap">git://jules.scsys.co.uk/gitmo/moose-presentations</span></li>
3790 <div class="slide fake-slide0">
3800 Copyright 2009 David Rolsky. All Rights Reserved.
3802 This work is licensed under a Creative Commons Attribution-Share Alike
3803 3.0 United States License See
3804 http://creativecommons.org/licenses/by-sa/3.0/us/ for details.