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="http://i.creativecommons.org/l/by-sa/3.0/us/88x31.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>
55 <h2><a href="git://git.moose.perl.org/moose-presentations.git"><tt>git://git.moose.perl.org/moose-presentations.git</tt></a></h2>
59 <h1>Moose Summed Up</h1>
62 <li><strong>Declarative</strong> OO sugar</li>
63 <li>Introspectable</li>
64 <li>Extensible (MooseX::* on CPAN)</li>
69 <h1>Moose Background</h1>
72 <li>Created by Stevan Little, first released in 2006</li>
73 <li>Moose builds on Perl 5's native OO</li>
74 <li>Borrows ideas from other languages, notably Perl 6</li>
75 <li>Provides semantics for common operations</li>
79 <div class="slide fake-slide0">
80 <h1>Part 0: Moose Concepts</h1>
93 <li>Method modifiers</li>
94 <li>Constructor and destructor</li>
95 <li>One metaclass object</li>
98 <li>Classes do roles</li>
103 <h1>Class Example</h1>
105 <pre><code>package Person;
106 <span class="highlight">use Moose;</span></code></pre>
109 <li>Poof, a Moose-based class!</li>
117 <li>Aka property, slot, field, member variable</li>
118 <li>A piece of data owned by an object</li>
129 <li>Access-control (read-only vs read-write)</li>
130 <li>An optional type</li>
131 <li>Accessor methods</li>
132 <li>Delegation methods</li>
133 <li>Optional default value</li>
134 <li>Many more features</li>
137 <li>Stored in the object, but don't worry about that</li>
142 <h1>Attribute Example</h1>
144 <pre><code>package Person;
147 <span class="highlight">has first_name => ( is => 'rw' );</span></code></pre>
155 <li>Nothing fancy here, just Perl subroutines</li>
158 <pre><code>package Person;
161 <span class="highlight">sub greet { ... }</span></code></pre>
168 <li>Classes <strong>do</strong> (or consume) roles</li>
169 <li>Similar to mixins and Java interfaces</li>
177 <li>Like classes, can have attributes, methods, do roles</li>
178 <li>Roles can require methods</li>
179 <li>Roles are composed (flattened) into classes</li>
184 <h1>Role Example</h1>
186 <pre><code>package HasPermissions;
187 <span class="highlight">use Moose::Role;</span>
189 has is_admin => ( is => 'rw' );</code></pre>
193 <h1>Role Example</h1>
199 <pre><code>package Person;
202 <span class="highlight">with 'HasPermissions';</span></code></pre>
206 <h1>Method Modifiers</h1>
210 <li>"<strong>Before</strong> foo(), do this first"</li>
211 <li>"Do this <strong>after</strong> foo()</li>
212 <li>"Put this code <strong>around</strong> foo()"</li>
217 <h1>Before and After</h1>
219 <pre><code>before 'foo'
220 => sub { warn 'About to call foo()' };
223 => sub { warn 'Leaving foo()' };</code></pre>
230 <pre><code>around 'foo' => sub {
231 my $real_foo = shift;
234 warn 'Just before foo()';
236 $self->$real_foo( @_, bar => 42 );
238 return ( @return, 'modify return values' );
243 <h1>Type Constraints</h1>
246 <li>NOT A FULL-BLOWN TYPE SYSTEM!</li>
247 <li>But still darn useful</li>
248 <li>Constrain attribute values</li>
249 <li>Coerce from other types</li>
254 <h1>Type Constraint Example</h1>
256 <pre><code>package Person;
261 <span class="highlight">isa => 'Int'</span>,
265 Person->new( weight => 'fat' );</code></pre>
272 <li>Attributes can define delegations</li>
273 <li>Lets you hide some implementation details</li>
274 <li>Fewer objects to chase around</li>
281 <pre><code>package Person;
287 <span class="highlight">handles => { 'blog_hostname' => 'host' },</span>
290 <span class="highlight">$person->blog_hostname;</span>
291 # really calls $person->blog_uri->host</code></pre>
295 <h1>Constructors</h1>
298 <li>Moose creates <code>new()</code> for you</li>
299 <li>Provide an optional <code>BUILDARGS()</code> and <code>BUILD()</code></li>
307 <li>Provide an optional <code>DEMOLISH()</code></li>
312 <h1>Moose Meta-API</h1>
315 <li>Answers questions like ...
317 <li>What methods does this class have?</li>
318 <li>What are its parents?</li>
319 <li>What attributes does it have (including inherited attributes)?</li>
320 <li>What roles does it do?</li>
321 <li>Much, much, more</li>
328 <h1>Moose Meta-API</h1>
331 <li>Not just for introspection ...
333 <li>Add methods, attributes, roles, etc</li>
334 <li>Extend and alter core features</li>
344 <li>A quick bit of propaganda ...</li>
351 <pre><code>package Person;
354 has last_name => (
361 <h1>Without Moose</h1>
363 <pre class="small"><code>package Person;
373 if (exists $args{last_name}) {
374 confess "Attribute (last_name) does not pass the type constraint because: "
375 . "Validation failed for 'Str' with value $args{last_name}"
376 if ref($args{last_name});
377 $self->{last_nane} = $args{last_name};
380 return bless $self, $class;
388 confess "Attribute (last_name) does not pass the type constraint because: "
389 . "Validation failed for 'Str' with value $value"
391 $self->{last_name} = $value;
394 return $self->{last_name};
400 <h1>Side by side</h1>
402 <table class="side-by-side">
405 <pre><code>package Person;
408 has last_name => (
414 <pre class="small"><code>package Person;
424 if (exists $args{last_name}) {
425 confess "Attribute (last_name) does not pass the type constraint because: "
426 . "Validation failed for 'Str' with value $args{last_name}"
427 if ref($args{last_name});
428 $self->{last_nane} = $args{last_name};
431 return bless $self, $class;
439 confess "Attribute (last_name) does not pass the type constraint because: "
440 . "Validation failed for 'Str' with value $value"
442 $self->{last_name} = $value;
445 return $self->{last_name};
454 <h1>Side by side</h1>
456 <table class="side-by-side">
459 <pre><code><span class="match-moose">package Person;</span>
462 has last_name => (
468 <pre class="small"><code><span class="match-unsweet">package Person;</span>
478 if (exists $args{last_name}) {
479 confess "Attribute (last_name) does not pass the type constraint because: "
480 . "Validation failed for 'Str' with value $args{last_name}"
481 if ref($args{last_name});
482 $self->{last_nane} = $args{last_name};
485 return bless $self, $class;
493 confess "Attribute (last_name) does not pass the type constraint because: "
494 . "Validation failed for 'Str' with value $value"
496 $self->{last_name} = $value;
499 return $self->{last_name};
507 <h1>Side by side</h1>
509 <table class="side-by-side">
512 <pre><code>package Person;
513 <span class="match-moose">use Moose;</span>
515 has last_name => (
521 <pre class="small"><code>package Person;
522 <span class="match-unsweet">use strict;
529 my $self = {};</span>
531 if (exists $args{last_name}) {
532 confess "Attribute (last_name) does not pass the type constraint because: "
533 . "Validation failed for 'Str' with value $args{last_name}"
534 if ref($args{last_name});
535 $self->{last_nane} = $args{last_name};
538 <span class="match-unsweet">return bless $self, $class;
546 confess "Attribute (last_name) does not pass the type constraint because: "
547 . "Validation failed for 'Str' with value $value"
549 $self->{last_name} = $value;
552 return $self->{last_name};
560 <h1>Side by side</h1>
562 <table class="side-by-side">
565 <pre><code>package Person;
568 <span class="match-moose">has last_name => (</span>
571 <span class="match-moose">);</span></code></pre>
574 <pre class="small"><code>package Person;
584 <span class="match-unsweet">if (exists $args{last_name}) {</span>
585 confess "Attribute (last_name) does not pass the type constraint because: "
586 . "Validation failed for 'Str' with value $args{last_name}"
587 if ref($args{last_name});
588 <span class="match-unsweet">$self->{last_nane} = $args{last_name};
591 return bless $self, $class;
599 confess "Attribute (last_name) does not pass the type constraint because: "
600 . "Validation failed for 'Str' with value $value"
602 $self->{last_name} = $value;
605 return $self->{last_name};
613 <h1>Side by side</h1>
615 <table class="side-by-side">
618 <pre><code>package Person;
621 has last_name => (
622 <span class="match-moose">is => 'rw',</span>
627 <pre class="small"><code>package Person;
637 if (exists $args{last_name}) {
638 confess "Attribute (last_name) does not pass the type constraint because: "
639 . "Validation failed for 'Str' with value $args{last_name}"
640 if ref($args{last_name});
641 $self->{last_nane} = $args{last_name};
644 return bless $self, $class;
647 <span class="match-unsweet">sub last_name {
651 my $value = shift;</span>
652 confess "Attribute (last_name) does not pass the type constraint because: "
653 . "Validation failed for 'Str' with value $value"
655 <span class="match-unsweet">$self->{last_name} = $value;
658 return $self->{last_name};
659 }</span></code></pre>
666 <h1>Side by side</h1>
668 <table class="side-by-side">
671 <pre><code>package Person;
674 has last_name => (
676 <span class="match-moose">isa => 'Str',</span>
680 <pre class="small"><code>package Person;
690 if (exists $args{last_name}) {
691 <span class="match-unsweet">confess "Attribute (last_name) does not pass the type constraint because: "
692 . "Validation failed for 'Str' with value $args{last_name}"
693 if ref($args{last_name});</span>
694 $self->{last_nane} = $args{last_name};
697 return bless $self, $class;
705 <span class="match-unsweet">confess "Attribute (last_name) does not pass the type constraint because: "
706 . "Validation failed for 'Str' with value $value"
707 if ref($value);</span>
708 $self->{last_name} = $value;
711 return $self->{last_name};
719 <h1>Side by side</h1>
721 <table class="side-by-side">
722 <tr class="incremental">
726 <tr class="incremental">
727 <td>92 characters</td>
728 <td>741 characters</td>
732 <pre><code>package Person;
735 has last_name => (
741 <pre class="small"><code>package Person;
751 if (exists $args{last_name}) {
752 confess "Attribute (last_name) does not pass the type constraint because: "
753 . "Validation failed for 'Str' with value $args{last_name}"
754 if ref($args{last_name});
755 $self->{last_nane} = $args{last_name};
758 return bless $self, $class;
766 confess "Attribute (last_name) does not pass the type constraint because: "
767 . "Validation failed for 'Str' with value $value"
769 $self->{last_name} = $value;
772 return $self->{last_name};
782 <pre class="small"><code>sub new {
787 if (exists $args{last_name}) {
788 confess "Attribute (last_name) does not pass the type constraint because: "
789 . "Validation failed for 'Str' with value $args{last_name}"
790 if ref($args{last_name});
791 $self->{last_nane} = $args{last_name};
794 return bless $self, $class;
801 <pre class="small"><code>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};
812 <code>$self->{last_nane} = $args{last_name};</code>
817 <code>$self->{last_na<span class="wrong">n</span>e}</code>
823 <pre><code>package Person;
826 has last_name => (
832 <div class="slide fake-slide0">
833 <h1>Part 1: Moose Classes</h1>
837 <h1>Moose Classes</h1>
840 <li>Moose classes are Perl packages which <code>use Moose</code></li>
845 <h1>Moose.pm and Your Class</h1>
847 <pre><code>package Person;
848 use Moose;</code></pre>
851 <li><code>Moose.pm</code> provides declarative sugar</li>
852 <li>Turns on <code>strict</code> and <code>warnings</code></li>
853 <li>Creates metaclasses for your class: <code>Person->meta</code></li>
854 <li>Moose classes automatically inherit from <code>Moose::Object</code></li>
859 <h1>What <code>Moose::Object</code> Provides</h1>
862 <li>Constructor - <code>new()</code></li>
863 <li>Calls your <code>BUILDARGS()</code> and/or <code>BUILD()</code></li>
864 <li>Calls your <code>DEMOLISH</code> during object destruction</li>
872 <li>Takes <code>@_</code>, returns a hash reference of attribute names/value</li>
873 <li>Accepts a hash or hashref; throws otherwise</li>
874 <li>Provide your own for other cases</li>
875 <li><strong>Always</strong> call <code>$class->SUPER::BUILDARGS(@_)</code> as a fallback!</li>
880 <h1>BUILDARGS Example</h1>
882 <pre><code>package Person;
888 if ( @_ == 1 && ! ref $_[0] ) {
889 <span class="highlight">return { ssn => $_[0] };</span>
892 <span class="highlight">return $class->SUPER::BUILDARGS(@_)</span>;
895 <span class="highlight">Person->new('123-45-6789')</span></code></pre>
902 <li>Called after object is created, before <code>new</code> returns</li>
903 <li>Chance to do more complex validation, set complex attributes</li>
904 <li>Called in reverse inheritance order, parents to children</li>
905 <li>Return value is ignored</li>
910 <h1>BUILD Example</h1>
912 <pre><code>package Person;
918 if ( $self->country_of_residence
920 die 'All US residents'
921 . ' must have an SSN'
922 unless $self->has_ssn;
928 <h1>Object Construction a la Moose</h1>
930 <pre><code>Person->new(@_)</code></pre>
933 <li>Calls <code>Person->BUILDARGS(@_)</code> to turn <code>@_</code> into a hashref</li>
934 <li>Blesses a reference</li>
935 <li>Populates attributes based on the hashref from #1</li>
936 <li>Calls <code>$new_object->BUILDALL($constructor_args)</code>
937 <br />... which calls all <code>BUILD</code> methods</li>
938 <li>Returns the object</li>
943 <h1>The Object is Opaque</h1>
946 <li>Technically it's a hash reference</li>
947 <li><span class="wrong">If you <em>ever</em> treat it as one <strong>you are doing it wrong!</strong></span></li>
955 <li>Like <code>DESTROY</code>, but Moose makes sure all <code>DEMOLISH</code> methods in a hierarchy are called</li>
956 <li>Called in normal inheritance order, children to parents</li>
964 <li><code>extends</code> is sugar for declaring parent classes</li>
967 <pre><code>package Employee;
969 <span class="highlight">extends 'Person';</span></code></pre>
976 <li>Each call to <code>extends</code> <strong>resets</strong> your parents</li>
979 <h2 class="wrong">Wrong</h2>
981 <pre><code>package EvilEmployee;
984 extends 'Thief';</code></pre>
986 <h2 class="right">Right</h2>
988 <pre><code>package EvilEmployee;
990 extends 'Person', 'Thief';</code></pre>
994 <h1>Extending un-Moose-y Parents</h1>
996 <pre><code>package My::LWP;
998 extends 'LWP';</code></pre>
1001 <li>No <code>Moose::Object</code>, so ...
1003 <li>No attribute-handling <code>new()</code></li>
1004 <li>No <code>BUILDARGS()</code> or <code>BUILD()</code></li>
1005 <li>No <code>DEMOLISH()</code></li>
1008 <li>But see <code>MooseX::NonMoose</code> for a workaround</li>
1013 <h1><code>override</code> and <code>super</code></h1>
1016 <li><code>override</code> is another method modifier</li>
1017 <li>An alternative to Perl's <code>SUPER::</code></li>
1022 <h1><code>override</code> and <code>super</code></h1>
1024 <pre><code>package Employee;
1027 <span class="current incremental">extends 'Person';</span>
1029 <span class="incremental">override</span> work => sub {
1032 die "Pay me first" unless $self->got_paid;
1033 <span class="incremental">super();</span>
1034 }<span class="incremental">;</span></code></pre>
1038 <h1>Caveat <code>super</code></h1>
1041 <li>Mostly like <code>$self->SUPER::work(@_)</code></li>
1042 <li><strong>But</strong> cannot change <code>@_</code>!</li>
1043 <li>Binds the parent's method at compile time</li>
1048 <h1>Minimal Attributes</h1>
1051 <li><code>has 'foo'</code></li>
1052 <li>Use <code>is => 'ro'</code> or <code>is => 'rw'</code></li>
1053 <li>Attributes without "is" have no accessors</li>
1058 <h1>Read-write attributes</h1>
1060 <pre><code>package Person;
1063 has first_name => ( <span class="highlight">is => 'rw'</span> );
1066 Person->new( first_name => 'Dave' );
1068 $person->first_name('Stevan');
1069 print $person->first_name; # Stevan</code></pre>
1074 <h1>Read-only attributes</h1>
1076 <pre><code>package Person;
1079 has first_name => ( <span class="highlight">is => 'ro'</span> );
1082 Person->new( first_name => 'Dave' );
1084 $person->first_name('Stevan');
1085 print $person->first_name; # Dave</code></pre>
1090 <h1>There is More to Come</h1>
1093 <li>Attributes have a <em>lot</em> of features</li>
1098 <h1>Cleaning Up Moose Droppings</h1>
1100 <pre><code>package Person;
1104 Person->can('extends');</code></pre>
1107 <li>Not very hygienic</li>
1112 <h1>Cleaning Up Moose Droppings</h1>
1114 <pre><code>package Person;
1122 Person->can('extends');</code></pre>
1129 <li><code>no Moose</code> at the end of a package is a best practice</li>
1130 <li>Or <code>namespace::clean</code> at the top</li>
1136 <h1>Immutability</h1>
1139 <li><span style="font-family: URW Chancery L; font-size: 140%">Stevan's Incantation of Fleet-Footedness</span></li>
1142 <pre><code>package Person;
1145 <span class="highlight">__PACKAGE__->meta->make_immutable;</span></code></pre>
1149 <h1>What <code>make_immutable</code> does</h1>
1153 <li>Uses <code>eval</code> to "inline" a constructor</li>
1154 <li>Memoizes a lot of meta-information</li>
1155 <li>Makes loading your class slower</li>
1156 <li>Makes object creation <em>much</em> faster</li>
1161 <h1>When to Immutabilize?</h1>
1164 <li><em>Almost</em> always</li>
1165 <li>Startup time vs execution time</li>
1170 <h1>Classes Summary</h1>
1173 <li><code>use Moose</code></li>
1174 <li><code>Class->meta</code></li>
1175 <li><code>Moose::Object</code> base class</li>
1176 <li><code>extends</code>, <code>override</code>, and <code>super</code></li>
1177 <li>Simple attributes: <code>has</code>, <code>is => 'ro'</code>, & <code>is => 'rw'</code></li>
1178 <li><code>no Moose</code></li>
1179 <li><code>__PACKAGE__->meta->make_immutable</code></li>
1192 # perl bin/prove -lv t/00-prereq.t
1194 # perl install-moose (if needed)
1196 # perl bin/prove -lv t/01-classes.t
1198 Iterate til this passes all its tests</pre>
1201 <div class="slide fake-slide0">
1202 <h1>Part 2: Roles</h1>
1206 <h1>Just What Is a Role?</h1>
1209 <li>Mixin? Interface? Trait?</li>
1210 <li>Yes ... and more!</li>
1215 <h1>Roles Can Have State <strong>and</strong> Behavior</h1>
1217 <pre><code>package HasPermissions;
1220 <span class="current incremental"># state
1221 has access_level => ( is => 'rw' );</span>
1223 <span class="incremental"># behavior
1226 my $required = shift;
1228 return $self->access_level >= $required;
1229 }</span></code></pre>
1234 <h1>Roles Can Define Interfaces</h1>
1236 <pre><code>package Printable;
1239 requires 'as_string';</code></pre>
1243 <h1>Roles Can Do All Three</h1>
1245 <pre><code>package Printable;
1248 requires 'as_string';
1250 has has_been_printed => ( is => 'rw' );
1254 print $self->as_string;
1255 $self->has_been_printed(1);
1260 <h1>Classes Consume Roles</h1>
1262 <pre><code>package Person;
1265 with 'HasPermissions';</code></pre>
1269 <h1>Classes Consume Roles</h1>
1271 <pre><code>my $person = Person->new(
1272 first_name => 'Kenichi',
1273 last_name => 'Asai',
1274 access_level => 42,
1277 print $person->full_name
1279 . $person->can_access(42)
1281 : 'little power';</code></pre>
1285 <h1>Roles in Practice</h1>
1288 <li>Consuming a role =~ inlining the role</li>
1293 <h1>In Other Words ...</h1>
1295 <pre><code>package Person;
1298 <span class="highlight">with 'Printable';</span></code></pre>
1302 <h1>In Other Words ...</h1>
1304 <pre><code>package Person;
1307 <span class="delete">with 'Printable';</span>
1309 <span class="highlight">has has_been_printed => ( is => 'rw' );
1313 print $self->as_string;
1314 $self->has_been_printed(1);
1315 }</span></code></pre>
1322 <li>Role consumption is introspectable</li>
1325 <pre><code>if ( Person->does('Printable') ) { ... }
1329 if ( Person->meta->does('Printable') ) { ... }</code></pre>
1334 <h1>These Names Are the Same</h1>
1337 <li>What if a role and class define the same method?</li>
1338 <li>A class's <em>local</em> methods win over the role's</li>
1339 <li>The role's methods win over the class's <em>inherited</em> methods</li>
1344 <h1>Conflicts Between Roles</h1>
1347 <li>Two roles with a method of the same name</li>
1348 <li>Generates a compile-time error when consumed by a class</li>
1353 <h1>Conflict Example</h1>
1355 <pre><code>package IsFragile;
1360 package CanBreakdance;
1363 sub break { ... }</code></pre>
1367 <h1>Conflict Example</h1>
1369 <pre><code>package FragileDancer;
1372 <span class="highlight">with 'IsFragile', 'CanBreakdance';</span></code></pre>
1375 <li>Only one <code>with</code>!</li>
1380 <h1>Conflict Resolution</h1>
1383 <li>The consuming class must resolve the conflict by implementing the method</li>
1384 <li>Can use some combination of method exclusion and aliasing</li>
1389 <h1>Method Aliasing</h1>
1391 <pre><code>package FragileDancer;
1394 <span class="highlight">with 'IsFragile' =>
1396 { break => 'break_bone' } },
1399 { break => 'break_it_down' } };</span></code></pre>
1402 <li>Renames the roles' methods</li>
1403 <li>Still conflicts, need to <code>exclude</code> as well</li>
1408 <h1>Method Exclusion</h1>
1410 <pre><code>package FragileDancer;
1413 <span class="highlight">with 'IsFragile' =>
1415 { break => 'break_bone' },
1416 exclude => 'break' },
1419 { break => 'break_dance' },
1420 exclude => 'break' };</span></code></pre>
1424 <h1>And then ...</h1>
1426 <pre><code>package FragileDancer;
1433 if ( rand(1) < 0.5 ) {
1440 <h1>Still Full of Fail</h1>
1443 <li>Roles are also about semantics!</li>
1444 <li>We've fulfilled the letter and lost the spirit</li>
1445 <li>Roles have a <em>meaning</em></li>
1446 <li>Think twice before blindly aliasing and excluding methods!</li>
1451 <h1>Hot Role-on-Role Action</h1>
1453 <pre><code>package Comparable;
1456 requires 'compare';</code></pre>
1460 <h1>Hot Role-on-Role Action</h1>
1462 <pre><code>package TestsEquality;
1469 return $self->compare(@_) == 0;
1474 <h1>And then ...</h1>
1476 <pre><code>package Integer;
1479 with 'TestsEquality';
1481 # Satisfies the Comparable role
1484 Integer->does('TestsEquality'); # true
1485 Integer->does('Comparable'); # also true!</code></pre>
1489 <h1>Name Conflicts Between Roles</h1>
1491 <pre><code>package HasSubProcess;
1494 <span class="highlight">sub execute { ... }</span>
1499 with 'HasSubProcess';
1501 <span class="highlight">sub execute { ... }</span></code></pre>
1505 <h1>Delayed Conflict</h1>
1507 <pre><code>package StateOfTexas;
1508 with 'Killer';</code></pre>
1511 <li><code>StateOfTexas</code> must implement its own <code>execute</code></li>
1512 <li>But loading the <code>Killer</code> role by itself does not cause an error</li>
1517 <h1>Roles as Interfaces</h1>
1520 <li>Roles can <code>require</code> methods of their consumers</li>
1521 <li>Compile-time checks</li>
1522 <li>Method must exist when the role is consumed</li>
1527 <h1>The Attribute Gotcha</h1>
1529 <pre><code>package HasSize;
1532 <span class="current incremental">requires 'size';</span>
1537 <span class="incremental">with 'HasSize';
1539 has size => ( is => 'ro' );</span></code></pre>
1543 <h1>The Attribute Gotcha Workaround</h1>
1545 <pre><code>package HasSize;
1553 has size => ( is => 'ro' );
1555 with 'HasSize';</code></pre>
1559 <h1>Compile-time Is a Lie</h1>
1562 <li>Really, it's <em>package load</em> time</li>
1563 <li>That's run-time, but before the "real" run-time</li>
1564 <li>Moose does not rewire Perl, it's just sugar!</li>
1565 <li>(but <code>MooseX::Declare</code> <em>does</em> rewire Perl)</li>
1570 <h1>Enforcing Roles</h1>
1572 <pre><code>package Comparison;
1575 has [ 'left', 'right' ] => (
1577 <span class="highlight">does => 'Comparable',</span>
1582 <li>A sneak peek at type constraints</li>
1588 <h1>Roles Can Be Applied to Objects</h1>
1590 <pre><code>use Moose::Util qw( apply_all_roles );
1592 my $fragile_person = Person->new( ... );
1593 apply_all_roles( $fragile_person, 'IsFragile' );</code></pre>
1596 <li>Does not change the <code>Person</code> class</li>
1597 <li>Works with non-Moose classes, great for monkey-patching!</li>
1602 <h1>Roles Are Dirty Too</h1>
1605 <li>Once again, clean up those Moose droppings</li>
1608 <pre><code>package Comparable;
1613 <span class="highlight">no Moose::Role;</span></code></pre>
1616 <li>But roles cannot be made immutable</li>
1621 <h1>The Zen of Roles</h1>
1624 <li>Roles represent discrete units of ...
1631 <li>Roles are shareable between unrelated classes</li>
1632 <li>Roles are what a class <em>does</em>, not what it <em>is</em></li>
1633 <li>Roles <em>add</em> functionality, inheritance <em>specializes</em></li>
1638 <h1>Abstract Examples</h1>
1641 <li>Human <em>@ISA</em> Animal</li>
1642 <li>Human <em>does</em> Toolmaker (as <em>does</em> Chimpanzee)</li>
1643 <li>Car <em>@ISA</em> Vehicle</li>
1644 <li>Car <em>does</em> HasEngine</li>
1649 <h1>Real Examples</h1>
1652 <li>Objects representing SQL database components and queries
1654 <li>Schema, Table, Column, ColumnAlias</li>
1655 <li>Select, Insert, Update, Delete</li>
1662 <h1>Real Examples</h1>
1665 <li>Column and ColumnAlias both <em>do</em> ColumnLike</li>
1666 <li>ColumnLike things can be used in certain parts of queries</li>
1667 <li>All queries <em>do</em> HasWhereClause</li>
1668 <li>Select <em>does</em> Comparable and Selectable (for subselects)</li>
1669 <li>A where clause requires its components to <em>do</em> Comparable</li>
1674 <h1>Roles Summary</h1>
1677 <li>Roles can define an interface with <code>requires</code></li>
1678 <li>Roles can have state (attributes) and behavior (methods)</li>
1679 <li>Roles can mix interface, state, & behavior</li>
1680 <li>Roles are composed (flattened) into classes</li>
1681 <li>Roles can do other roles</li>
1682 <li>Roles can be used as a type in APIs (must do Comparable)</li>
1694 # perl bin/prove -lv t/02-roles.t
1696 Iterate til this passes all its tests</pre>
1699 <div class="slide fake-slide0">
1700 <h1>Part 3: Basic Attributes</h1>
1704 <h1>Attributes Are Huge</h1>
1707 <li>Moose's biggest feature</li>
1708 <li>The target of <em>many</em> MooseX modules</li>
1713 <h1>Quick Review</h1>
1716 <li>Declared with <code>has</code></li>
1717 <li>Read-only or read-write</li>
1720 <pre><code>package Shirt;
1723 has 'color' => ( is => 'ro' );
1724 has 'is_ripped' => ( is => 'rw' );</code></pre>
1728 <h1>Required-ness</h1>
1731 <li>Required means "must be passed to the constructor"</li>
1732 <li>But can be <code>undef</code></li>
1737 <h1>Required-ness</h1>
1739 <pre><code>package Person;
1742 has first_name => (
1744 <span class="current incremental">required => 1,</span>
1747 <span class="incremental">Person->new( first_name => undef ); # ok
1748 Person->new(); # kaboom</span></code></pre>
1752 <h1>Default and Builder</h1>
1755 <li>Attributes can have defaults</li>
1756 <li>Simple non-referecne scalars (number, string)</li>
1757 <li>Subroutine reference</li>
1758 <li>A builder method</li>
1766 <li>Can be a non-reference scalar (including <code>undef</code>)</li>
1769 <pre><code>package Person;
1774 default => 'Spire FCU',
1782 <li>Can be a subroutine reference</li>
1785 <pre><code>package Person;
1792 name => 'Spire FCU' ) },
1797 <h1>Default as a Subroutine Reference</h1>
1800 <li>Called as a method on the object</li>
1801 <li>Called anew for each object</li>
1806 <h1>Why No Other Reference Types?</h1>
1808 <pre><code>package Person;
1813 <span class="wrong">default => Bank->new(
1814 name => 'Spire FCU' ),</span>
1818 <li>Now <strong>every</strong> person shares the <strong>same</strong> Bank object!</li>
1823 <h1>Defaulting to an Empty Reference</h1>
1825 <pre><code>package Person;
1828 has packages => (
1830 default => <span class="highlight">sub { [] }</span>,
1835 <h1>What if I Want to Share?</h1>
1837 <pre><code>package Person;
1840 my $highlander_bank =
1841 Bank->new( name => 'Spire FCU' );
1845 default => sub { $highlander_bank },
1853 <li>A method <em>name</em> which returns the default</li>
1860 <pre><code>package Person;
1865 builder => '_build_bank',
1870 return Bank->new( name => 'Spire FCU' );
1875 <h1>Default vs Builder</h1>
1878 <li>Use default for simple scalars</li>
1879 <li>Use default to return empty references</li>
1880 <li>Use default for <em>very</em> trivial subroutine references</li>
1881 <li>Use builder for everything else</li>
1886 <h1>Builder Bonuses</h1>
1889 <li>Can be overridden and method modified, because it's called by <em>name</em></li>
1890 <li>Roles can require a builder</li>
1895 <h1>Role Requires Builder</h1>
1897 <pre><code>package HasBank;
1900 requires '_build_bank';
1904 builder => '_build_bank',
1909 <h1>Lazy, Good for Nothing Attributes</h1>
1912 <li>Normally, defaults are generated during object construction</li>
1913 <li>This can be expensive</li>
1914 <li>We want to default to <code>$self->size * 2</code>, but attribute initialization order is unpredictable</li>
1915 <li>Use lazy attributes!</li>
1920 <h1>The Power of Dynamic Defaults</h1>
1922 <pre><code>package Person;
1925 has shoe_size => (
1931 <h1>The Power of Dynamic Defaults</h1>
1933 <pre><code>has shoes => (
1935 <span class="highlight">lazy => 1,</span>
1936 builder => '_build_shoes',
1942 return Shoes->new(
1943 size => <span class="highlight">$self->shoe_size</span> );
1948 <h1>Lazy is Good</h1>
1951 <li>Lazy defaults are executed when the attribute is read</li>
1952 <li>Can see other object attributes</li>
1953 <li>Still need to watch out for circular laziness</li>
1958 <h1>Clearer and Predicate</h1>
1961 <li>Attributes can have a value, including <code>undef</code>, or not</li>
1962 <li>Can clear the value with a clearer method</li>
1963 <li>Can check for the existence of a value with a predicate method</li>
1964 <li>By default, these methods are not created</li>
1969 <h1>Clearer and Predicate</h1>
1971 <pre><code>package Person;
1977 builder => '_build_account',
1978 <span class="highlight">clearer => '_clear_account',
1979 predicate => 'has_account',</span>
1984 <h1>Clearer and Lazy Defaults</h1>
1987 <li>Lazy defaults are good for computed attributes</li>
1988 <li>Clear the attribute when the source data changes</li>
1989 <li>Recalculated at next access</li>
1994 <h1>Renaming constructor arguments</h1>
1997 <li>By default, constructor names = attribute names</li>
1998 <li>Use <code>init_arg</code> to change this</li>
1999 <li>Set <code>init_arg => undef</code> to make it unconstructable</li>
2004 <h1>Some <code>init_arg</code> examples</h1>
2006 <pre><code>package Person;
2011 <span class="highlight">init_arg => 'foot_size',</span>
2014 Person->new( <span class="wrong">shoe_size => 13</span> );
2017 Person->new( <span class="right">foot_size => 13</span> );
2018 print $person->shoe_size;</code></pre>
2022 <h1>Some <code>init_arg</code> examples</h1>
2024 <pre><code>package Person;
2029 <span class="highlight">init_arg => undef,</span>
2032 Person->new( <span class="wrong">shoes => Shoes->new</span> );</code></pre>
2036 <h1>Why Set <code>init_arg => undef</code>?</h1>
2039 <li>Use this with a lazy default for attributes-as-cache</li>
2040 <li>Compute the value as needed</li>
2041 <li>Ensure that it is always generated correctly (not set by constructor)</li>
2042 <li>Use triggers or method modifiers (coming soon) to clear the value</li>
2047 <h1>Attribute Inheritance</h1>
2050 <li>By default, subclasses inherit attribute as-is</li>
2051 <li>Can change some attribute parameters in subclasses
2057 <li>others we've not yet covered</li>
2064 <h1>Attribute Inheritance Example</h1>
2066 <pre><code>package Employee;
2071 has '<span class="highlight">+first_name</span>' => (
2072 default => 'Joe',
2077 <h1>Attribute Inheritance Warning</h1>
2080 <li>An attribute is a contract about a class's API</li>
2081 <li>Don't break that contract in a subclass</li>
2082 <li>Especially important in the context of types</li>
2087 <h1>Changing Accessor Names</h1>
2089 <pre><code>package Person;
2092 has first_name => (
2093 <span class="highlight">accessor</span> => 'first_name',
2097 <li>The long-hand version of <code>is => 'rw'</code></li>
2102 <h1>Changing Accessor Names</h1>
2104 <pre><code>package Person;
2107 has first_name => (
2108 <span class="highlight">reader</span> => 'first_name',
2109 <span class="highlight">writer</span> => undef,
2113 <li>The long-hand version of <code>is => 'ro'</code></li>
2119 <h1>Changing Accessor Names</h1>
2121 <pre><code>package Person;
2124 has first_name => (
2125 <span class="highlight">reader</span> => 'get_first_name',
2126 <span class="highlight">writer</span> => 'set_first_name',
2131 <h1>Changing Accessor Names</h1>
2133 <pre><code>package Person;
2136 has first_name => (
2137 <span class="highlight">is</span> => 'rw',
2138 <span class="highlight">writer</span> => '_first_name',
2142 <li>Can also mix-and-match <code>is</code> and explicit names</li>
2147 <h1>ETOOMUCHTYPING</h1>
2150 <li><code>MooseX::FollowPBP</code><br /><code>get_foo</code> and <code>set_foo</code></li>
2151 <li><code>MooseX::SemiAffordanceAccessor</code><br /><code>foo</code> and <code>set_foo</code></li>
2156 <h1>ETOOMUCHTYPING</h1>
2158 <pre><code>package Person;
2160 <span class="highlight">use MooseX::SemiAffordanceAccessor;</span>
2162 has first_name => (
2167 <li>Creates <code>first_name</code> and <code>set_first_name</code></li>
2172 <h1>Basic Attributes Summary</h1>
2175 <li>Attributes can be <code>required</code></li>
2176 <li>Attributes can have a <code>default</code> or <code>builder</code></li>
2177 <li>Attributes with a default or builder can be <code>lazy</code></li>
2178 <li>Attributes can have a <code>clearer</code> and/or <code>predicate</code></li>
2179 <li>An attribute's constructor name can be changed with <code>init_arg</code></li>
2180 <li>A subclass can alter its parents' attributes</li>
2181 <li>Attribute accessor names can be changed</li>
2193 # perl bin/prove -lv t/03-basic-attributes.t
2195 Iterate til this passes all its tests</pre>
2198 <div class="slide fake-slide0">
2199 <h1>Part 4: Method Modifiers</h1>
2203 <h1>What is a Method Modifier</h1>
2206 <li>Apply to an existing method</li>
2207 <li>... from a parent class, the current class, or a role</li>
2208 <li>Roles can provide modifiers that are applied at composition time</li>
2213 <h1>What is a Method Modifier</h1>
2216 <li>"Inject" behavior</li>
2217 <li>Add behavior to generated methods (accessors, delegations)</li>
2218 <li>Provide roles which modify existing behavior</li>
2223 <h1>Before and After</h1>
2226 <li>Simplest modifiers - <code>before</code> and <code>after</code></li>
2227 <li>Guess when they run!</li>
2232 <h1>Uses for <code>before</code></h1>
2235 <li>As a pre-call check</li>
2238 <pre><code>package Person;
2241 before work => sub {
2243 die 'I have no job!'
2244 unless $self->has_title;
2249 <h1>Uses for <code>before</code></h1>
2252 <li>Logging/Debugging</li>
2255 <pre><code>package Person;
2258 before work => sub {
2260 return unless $DEBUG;
2262 warn "Called work on ", $self->full_name,
2263 "with the arguments: [@_]\n";
2268 <h1>Uses for <code>after</code></h1>
2271 <li>Also works for logging/debugging</li>
2272 <li>Post-X side-effects (recording audit info)</li>
2275 <pre><code>package Person;
2278 after work => sub {
2280 $self->work_count(
2281 $self->work_count + 1 );
2289 <li>Modifiers are useful for adding behavior to generated methods</li>
2294 <h1>Other Uses Example</h1>
2296 <pre><code>has password => (
2298 clearer => 'clear_password',
2301 has hashed_password => (
2303 builder => '_build_hashed_password',
2304 clearer => '_clear_hashed_password',
2307 after clear_password => sub {
2309 $self->_clear_hashed_password;
2314 <h1><code>before</code> and <code>after</code> Limitations</h1>
2317 <li>Cannot alter method parameters</li>
2318 <li>Cannot alter return value</li>
2319 <li>But <strong>can</strong> throw an exception</li>
2324 <h1>The <code>around</code> Modifier</h1>
2327 <li>The big gun</li>
2328 <li>Can alter parameters <strong>and/or</strong> return values</li>
2329 <li>Can skip calling the wrapped method entirely</li>
2334 <h1>The power of <code>around</code></h1>
2336 <pre><code>around insert => sub {
2340 $self->_validate_insert(@_);
2344 $self->_munge_insert(@_) );
2346 $new_user->_assign_uri;
2353 <h1>Modifier Order</h1>
2356 <li>Before runs order from last to first</li>
2357 <li>After runs in order from first to last</li>
2358 <li>Around runs in order from last to first</li>
2363 <h1>Modifier Order Illustrated</h1>
2366 <span class="current incremental">before 2
2368 <span class="incremental">around 2
2370 <span class="incremental">wrapped method</span>
2371 <span class="incremental">around 1
2373 <span class="incremental">after 1
2379 <h1>Modifiers in Roles</h1>
2382 <li>Roles can use these modifiers</li>
2383 <li>Very powerful!</li>
2388 <h1>Modifiers in Roles</h1>
2390 <pre><code>package IsUnreliable;
2393 <span class="highlight">requires 'run';
2395 around run</span> => sub {
2399 return if rand(1) < 0.5;
2401 return $self->$orig(@_);
2406 <h1>Augment and Inner</h1>
2409 <li>Inverted <code>super</code></li>
2410 <li>From least- to most-specific</li>
2411 <li>Grandparent to parent to child</li>
2412 <li>Not allowed in roles</li>
2417 <h1>Augment and Inner</h1>
2419 <pre><code>package Document;
2421 sub xml { '<doc>' . <span class="highlight">inner()</span> . '</doc>' }
2426 <span class="highlight">augment xml</span> =>
2427 sub { title() . <span class="highlight">inner()</span> . summary() };
2432 <span class="highlight">augment xml</span> =>
2433 sub { tps_xml() . <span class="highlight">inner()</span> };</code></pre>
2437 <h1>Augment and Inner</h1>
2440 <li>When we call <code>$tps->xml</code> ...
2442 <li><code>Document->xml</code></li>
2443 <li><code>Report->xml</code></li>
2444 <li><code>TPSReport->xml</code></li>
2451 <h1>Augment and Inner Usage</h1>
2454 <li>Call <code>inner()</code> to "fill in the blank"</li>
2455 <li>Requires designing for subclassing</li>
2456 <li>Call <code>inner()</code> in the terminal class, just in case</li>
2461 <h1>Method Modifiers Summary</h1>
2464 <li>Use <code>before</code> and <code>after</code> for ...
2467 <li>pre- or post-validation</li>
2468 <li>to add behavior to generated methods</li>
2471 <li>These two modifiers cannot change parameters or return values</li>
2476 <h1>Method Modifiers Summary</h1>
2479 <li>Use <code>around</code> to ...
2481 <li>alter parameters passed to the original method</li>
2482 <li>alter the return value of the original method</li>
2483 <li>not call the original method at all (or call a <em>different</em> method)</li>
2490 <h1>Method Modifiers Summary</h1>
2493 <li>When using modifiers in a role, require the modified method</li>
2494 <li>Use <code>augment</code> and <code>inner</code> to invert the normal subclassing flow ...
2496 <li>Least- to most-specific (parents to children)</li>
2497 <li>Build in "insertability" (stick more stuff in the "middle")</li>
2500 <li>Always call <code>inner</code> in the most specific subclass to allow for future extension</li>
2512 # perl bin/prove -lv t/04-method-modifiers.t
2514 Iterate til this passes all its tests</pre>
2517 <div class="slide fake-slide0">
2518 <h1>Part 5: Types</h1>
2522 <h1>A Type System for Perl</h1>
2525 <li>Sort of ...</li>
2526 <li><em>Variables</em> are not typed</li>
2527 <li>Attributes can have types</li>
2528 <li>MooseX modules let you define method signatures</li>
2533 <h1>Components of a Moose Type</h1>
2536 <li>A type is a name and a constraint</li>
2537 <li>Types have a hierarchy</li>
2538 <li>Constraints are cumulative from parents</li>
2539 <li>Types can have associated coercions</li>
2544 <h1>Built-in Type Hierarchy</h1>
2563 <h1>Built-in Type Hierarchy</h1>
2596 <li>Like Perl's <code>if ($foo)</code></li>
2601 <h1>Value (and subtypes)</h1>
2604 <li><code>Value</code> is true when <code>! ref $thing</code></li>
2605 <li><code>Value</code> and <code>Str</code> are effectively the same, but <code>Str</code> is more expressive</li>
2606 <li>An overloaded object which numifies does not pass the <code>Num</code> constraint!</li>
2607 <li>Perl 5's overloading is hopelessly broken</li>
2612 <h1>ClassName and RoleName</h1>
2615 <li>A string with a package name</li>
2616 <li>The package <strong>must already be loaded</strong></li>
2621 <h1>Parameterizable Types</h1>
2624 <li>What does <code>ArrayRef[`a]</code> mean?</li>
2625 <li><code>s/`a/Int/</code> (or <code>Str</code> or ...)</li>
2626 <li>When you use it you can write ...
2628 <li><code>ArrayRef</code> (== <code>ArrayRef[Item]</code>)</li>
2629 <li><code>ArrayRef[Str]</code></li>
2630 <li><code>ArrayRef[MyTypeName]</code></li>
2631 <li><code>ArrayRef[HashRef[Maybe[Int]]]</code></li>
2641 <li>Maybe means either the named type or <code>undef</code></li>
2642 <li><code>Maybe[Int]</code> accepts integers or <code>undef</code></li>
2650 <li>This or that (or that or ...)</li>
2651 <li><code>Int | ArrayRef[Int]</code></li>
2652 <li>But use a coercion instead when possible</li>
2653 <li>Or use a <code>role_type</code>, <code>duck_type</code>, or anything not a union</li>
2654 <li>A union is often a code smell</li>
2659 <h1>Making Your Own Types</h1>
2661 <pre><code>use Moose::Util::TypeConstraints;
2663 <span class="incremental current">subtype 'PositiveInt',</span>
2664 <span class="incremental">as 'Int',</span>
2665 <span class="incremental">where { $_ > 0 },</span>
2666 <span class="incremental">message { "The value you provided ($_)"
2667 . " was not a positive number." };</span>
2671 <span class="incremental">isa => 'PositiveInt',</span>
2676 <h1>Automatic Types</h1>
2679 <li>Moose creates a type for every Moose class and role</li>
2680 <li>Unknown names are assumed to be classes</li>
2685 <h1>Automatic Types</h1>
2687 <pre><code>package Employee;
2692 <span class="highlight">isa => 'Employee',</span>
2695 has start_date => (
2697 <span class="highlight">isa => 'DateTime',</span>
2702 <h1>Subtype Shortcuts - <code>class_type</code></h1>
2704 <pre><code>use Moose::Util::TypeConstraints;
2705 class_type 'DateTime';
2709 where { $_->isa('DateTime') },
2710 message { ... };</code></pre>
2714 <h1>Subtype Shortcuts - <code>role_type</code></h1>
2716 <pre><code>use Moose::Util::TypeConstraints;
2717 role_type 'Printable';
2719 subtype 'Printable',
2722 { Moose::Util::does_role(
2723 $_, 'Printable' ) },
2724 message { ... };</code></pre>
2728 <h1>Subtype Shortcuts - <code>duck_type</code></h1>
2730 <pre><code>use Moose::Util::TypeConstraints;
2731 duck_type Car => qw( run break_down );
2735 where { all { $_->can($_) }
2736 qw( run break_down ) },
2737 message { ... };</code></pre>
2741 <h1>Subtype Shortcuts - <code>enum</code></h1>
2743 <pre><code>use Moose::Util::TypeConstraints;
2744 enum Color => qw( red blue green ) );
2746 my %ok = map { $_ => 1 } qw( red blue green );
2750 message { ... };</code></pre>
2754 <h1>Anonymous Subtypes</h1>
2756 <pre><code>package Person;
2758 <span class="highlight">my $posint =
2759 subtype as 'Int', where { $_ > 0 };</span>
2763 <span class="highlight">isa => $posint,</span>
2767 <li>Shortcuts have anonymous forms as well</li>
2774 <pre><code>use Moose::Util::TypeConstraints;
2778 where { ! /[a-z]/ };
2780 <span class="incremental current">coerce 'UCStr',</span>
2781 <span class="incremental">from 'Str',</span>
2782 <span class="incremental">via { uc };</span>
2784 has shouty_name => (
2787 <span class="incremental">coerce => 1,</span>
2792 <h1>Coercion Examples</h1>
2794 <pre><code>subtype 'My::DateTime',
2795 as class_type 'DateTime';
2797 coerce 'My::DateTime',
2799 via { DateTime->new( %{$_} ) };
2801 coerce 'My::DateTime',
2803 via { DateTime->from_epoch(
2804 epoch => $_ ) };</code></pre>
2807 <li>Use coercion to inflate a value</li>
2812 <h1>Coercion Examples</h1>
2814 <pre><code>coerce 'ArrayRef[Int]',
2816 via { [ $_ ] };</code></pre>
2819 <li>Coerce instead of a union like <code style="white-space: nowrap">Int | ArrayRef[Int]</code></li>
2824 <h1>Using Types with Attributes</h1>
2826 <pre><code>package Person;
2828 use Moose::Util::TypeConstraints;
2832 <span class="highlight">isa => 'Num',</span>
2835 has favorite_numbers => (
2837 <span class="highlight">isa => 'ArrayRef[Int]',
2838 coerce => 1,</span>
2843 <h1>More Droppings</h1>
2846 <li><code>Moose::Util::TypeConstraint</code> also needs cleanup</li>
2849 <pre><code>package Person;
2852 use Moose::Util::TypeConstraints;
2857 <span class="highlight">no Moose::Util::TypeConstraints;</span></code></pre>
2861 <h1>Typed Methods (Low-tech)</h1>
2863 <pre class="medium"><code>package Person;
2864 <span class="highlight">use MooseX::Params::Validate qw( validated_list );</span>
2868 <span class="highlight">my ( $tasks, $can_rest ) =
2872 { isa => 'ArrayRef[Task]',
2884 <h1>Typed Methods (High-tech)</h1>
2886 <pre class="medium"><code>package Person;
2888 <span class="highlight">use MooseX::Method::Signatures;</span>
2890 <span class="highlight">method work ( ArrayRef[Task] :$tasks,
2891 Bool :$can_rest = 0 )</span> {
2899 <h1>Digression: The Type Registry</h1>
2902 <li>Types are actually <code>Moose::Meta::TypeConstraint</code> <em>objects</em></li>
2903 <li>Stored in an interpreter-global registry mapping names to objects</li>
2911 <li>Coercions are attached to type objects</li>
2912 <li>Therefore also global</li>
2913 <li>Name conflicts between modules!</li>
2914 <li>Coercion conflicts between modules!</li>
2919 <h1>Namespace Fix</h1>
2922 <li>Use some sort of pseudo-namespacing scheme</li>
2923 <li>Never coerce directly to a class name, or <em>to</em> built-in types</li>
2928 <h1>Namespace Fix</h1>
2930 <pre><code>use Moose::Util::TypeConstraints;
2932 subtype <span class="highlight">'MyApp::Type::DateTime',</span>
2935 <span class="highlight">coerce 'MyApp::Type::DateTime',</span>
2937 via { DateTime->new( %{$_} ) }
2939 has creation_date => (
2941 <span class="highlight">isa => 'MyApp::Type::DateTime',</span>
2947 <h1>Namespace Fix</h1>
2949 <pre><code>subtype 'MyApp::Type::ArrayOfInt',
2952 coerce 'MyApp::Type::ArrayOfInt',
2954 via { [ $_ ] };</code></pre>
2958 <h1>Namespace Fix Pros and Cons</h1>
2961 <li><span class="right">Relatively simple</span></li>
2962 <li><span class="right">Already built into Moose</span></li>
2963 <li><span class="wrong">Conflates type and module namespaces</span></li>
2964 <li><span class="wrong">Type names are strings, so typos are easy to make and may be hard to find</span></li>
2969 <h1>MooseX::Types</h1>
2971 <pre><code>package MyApp::Types;
2974 <span class="highlight">-declare => [ qw( ArrayOfInt ) ]</span>;
2975 use MooseX::Types::Moose
2978 subtype <span class="highlight">ArrayOfInt</span>,
2981 coerce <span class="highlight">ArrayOfInt</span>
2983 via { [ $_ ] };</code></pre>
2987 <h1>MooseX::Types</h1>
2989 <pre><code>package MyApp::Account;
2991 use MyApp::Types qw( ArrayOfInt );
2993 has transaction_history => (
3000 <h1>MooseX::Types</h1>
3003 <li>Type names are exported functions, catches typos early</li>
3004 <li>Types must be pre-declared</li>
3005 <li>Types are stored with namespaces internally, but externally are short</li>
3006 <li>Import existing Moose types as functions from <code>MooseX::Types::Moose</code></li>
3007 <li>Still need string names for things like <code>ArrayRef['Email::Address']</code></li>
3012 <h1>MooseX::Types Pros and Cons</h1>
3015 <li><span class="right">Catches typos at compile time</span></li>
3016 <li><span class="right">Automatic namespacing</span></li>
3017 <li><span class="wrong">One more thing to install and learn</span></li>
3018 <li><span class="wrong">Every name gets types twice (declared and then defined)</span></li>
3019 <li><span class="wrong">Still stuck with strings when referring to class or role names</span></li>
3020 <li><span class="wrong">Coercion gotcha from earlier still applies to types exported from <code>MooseX::Types::Moose</code></span></li>
3025 <h1>Recommendation</h1>
3028 <li>Use <code>MooseX::Types</code></li>
3029 <li>Compile time error catching and automatic namespacing are huge wins</li>
3030 <li>Docs from <code>Moose::Util::TypeConstraints</code> are 98% compatible with <code>MooseX::Types</code> anyway</li>
3031 <li>A function exported by a type library works wherever a type name would</li>
3043 # perl bin/prove -lv t/05-types.t
3045 Iterate til this passes all its tests</pre>
3048 <div class="slide fake-slide0">
3049 <h1>Part 6: Advanced Attributes</h1>
3053 <h1>Weak References</h1>
3056 <li>A weak reference lets you avoid circular references</li>
3057 <li>Weak references do not increase the reference count</li>
3062 <h1>Circular Reference Illustrated</h1>
3064 <pre><code>my $foo = {};
3065 my $bar = { foo => $foo };
3066 $foo->{bar} = $bar;</code></pre>
3069 <li>Neither <code>$foo</code> nor <code>$bar</code> go out of scope<br />
3070 (until the program exits)</li>
3075 <h1>Weakening Circular References</h1>
3077 <pre><code>use Scalar::Util qw( weaken );
3080 my $bar = { foo => $foo };
3081 $foo->{bar} = $bar;
3082 weaken $foo->{bar}</code></pre>
3085 <li>When <code>$bar</code> goes out of scope, <code>$foo->{bar}</code> becomes <code>undef</code></li>
3090 <h1>Circular References in Attributes</h1>
3092 <pre><code>package Person;
3095 has name => ( is => 'ro' );
3096 has friend => ( is => 'rw' );
3098 my $alice = Person->new( name => 'Alice' );
3099 my $bob = Person->new( name => 'Bob' );
3100 $bob->friend($alice);
3101 $alice->friend($bob);</code></pre>
3107 <pre><code>package Person;
3110 has name => ( is => 'ro' );
3111 has friend => ( is => 'rw', <span class="highlight">weak_ref => 1</span> );
3113 my $alice = Person->new( name => 'Alice' );
3114 my $bob = Person->new( name => 'Bob' );
3115 $bob->friend($alice);
3116 $alice->friend($bob);</code></pre>
3120 <h1>Under the Hood</h1>
3123 <li>A <code>weak_ref</code> attribute calls <code>weaken</code> ...
3125 <li>during object construction</li>
3126 <li>when the attribute is set via a writer</li>
3136 <li>A code reference run after an attribute is <em>set</em></li>
3137 <li>Like an <code>after</code> modifier, but makes intentions clearer</li>
3140 <h2 class="wrong">Gross</h2>
3142 <pre><code>after salary_level => {
3145 $self->clear_salary;
3150 <h1>Use a Trigger Instead</h1>
3152 <h2 class="right">Cleaner</h2>
3154 <pre><code>has salary_level => (
3156 trigger => sub { $_[0]->clear_salary },
3164 <li>Attributes can be objects</li>
3165 <li>Delegation transparently calls methods on those objects</li>
3170 <h1>Delegation Examples</h1>
3172 <pre><code>package Person;
3177 <span class="highlight">handles => [ 'inhale', 'exhale' ],</span>
3181 <li>Creates <code>$person->inhale</code> and <code>->exhale</code> methods</li>
3182 <li>Internally calls <code>$person->lungs->inhale</code></li>
3187 <h1>Why Delegation?</h1>
3190 <li>Reduce the number of classes exposed</li>
3191 <li>Re-arrange class internals -<br />
3192 turn a method into an attribute with delegation</li>
3193 <li>Provide convenenience methods</li>
3198 <h1>Moose's <code>handles</code> Parameter</h1>
3201 <li>Accepts many arguments ...
3203 <li>Array reference - list of methods to delegate as-is</li>
3204 <li>Hash reference - map of method names</li>
3205 <li>Regex - delegates all matching methods</li>
3206 <li>Role name - delegates all methods in the role</li>
3207 <li>Sub reference - does something complicated ;)</li>
3214 <h1>Array Reference</h1>
3217 <li>Takes each method name and creates a simple delegation from the delegating class to the delegatee attribute</li>
3222 <h1>Hash Reference</h1>
3225 <li>Mapping of names in the delegating class to the delegatee class</li>
3228 <pre><code>package Person;
3233 isa => 'BankAccount',
3234 <span class="highlight">handles => {
3235 receive_money => 'deposit',
3236 give_money => 'withdraw',
3242 <h1>Hash Reference Detailed</h1>
3244 <pre><code> handles => {
3245 receive_money => 'deposit',
3246 give_money => 'withdraw',
3250 <li><code>$person->receive_money</code> = <code>$person->account->deposit</code></li>
3251 <li><code>$person->give_money</code> = <code>$person->account->withdraw</code></li>
3258 <pre><code>package Person;
3264 handles => qr/.*/,
3268 <li>Creates a delegation for every method in the Name class</li>
3269 <li>Excludes <code>meta</code> and methods inherited from <code>Moose::Object</code></li>
3276 <pre><code>package Auditor;
3279 sub record_change { ... }
3280 sub change_history { ... }
3287 does => 'Auditor',
3288 <span class="highlight">handles => 'Auditor',</span>
3293 <h1>Role Name Detailed</h1>
3296 <li>Account gets delegate methods for each method in the <code>Auditor</code> role
3298 <li>record_history</li>
3299 <li>change_history</li>
3306 <h1>Native Delegation</h1>
3309 <li>Delegate to <em>unblessed</em> Perl types</li>
3310 <li>Scalar, array or hash ref, etc</li>
3315 <h1>Native Delegation - Array</h1>
3317 <pre><code>package Person;
3320 has _favorite_numbers => (
3321 traits => [ 'Array' ],
3323 isa => 'ArrayRef[Int]',
3324 default => sub { [] },
3325 init_arg => undef,
3326 <span class="highlight">handles =>
3327 { favorite_numbers => 'elements',
3328 add_favorite_number => 'push',
3333 <li>Automatically defaults to <code>[]</code></li>
3338 <h1>Native Delegation - Counter</h1>
3340 <pre><code>package Stack;
3344 traits => [ 'Counter' ],
3348 init_arg => undef,
3349 <span class="highlight">handles =>
3350 { _inc_depth => 'inc',
3351 _dec_depth => 'dec',
3358 <h1>Traits and Metaclasses</h1>
3361 <li>The ultimate in customization</li>
3362 <li>Per attribute metaclasses</li>
3363 <li>Per attribute roles applied to the attribute metaclass</li>
3364 <li>Change the meta-level behavior</li>
3369 <h1>Traits and Metaclasses</h1>
3372 <li>The default metaclass is <code>Moose::Meta::Attribute</code></li>
3373 <li>Controls accessor generation, defaults, delegation, etc.</li>
3374 <li>Adding a role to this metaclass (or replacing it) allows for infinite customization</li>
3379 <h1>Traits and Metaclasses</h1>
3382 <li>Can add/alter/remove attribute parameter (from <code>has</code>)</li>
3383 <li>Can change behavior of created attribute</li>
3388 <h1>Simple Trait Example</h1>
3390 <pre><code>package Person;
3392 use MooseX::LabeledAttributes;
3395 <span class="highlight">traits => [ 'Labeled' ],</span>
3398 <span class="highlight">label => 'Social Security Number',</span>
3401 print <span class="highlight">Person->meta
3402 ->get_attribute('ssn')->label;</span></code></pre>
3406 <h1>Simple Metaclass Example</h1>
3408 <pre><code>package Person;
3410 use MooseX::LabeledAttributes;
3413 <span class="highlight">metaclass =>
3414 'MooseX::Meta::Attribute::Labeled',</span>
3417 <span class="highlight">label => 'Social Security Number',</span>
3420 print <span class="highlight">Person->meta
3421 ->get_attribute('ssn')->label;</span></code></pre>
3425 <h1>Traits vs Metaclass</h1>
3428 <li>Can apply any mix of traits to an attribute</li>
3429 <li>But just one metaclass</li>
3430 <li>Traits (aka roles) can cooperate</li>
3431 <li>Metaclasses require you to pick just one</li>
3436 <h1>Advanced Attributes Summary</h1>
3439 <li>Use <code>weak_ref</code> to avoid circular references</li>
3440 <li>Use trigger to do an action post-attribute write</li>
3441 <li>Use delegations to hide "internal" objects</li>
3442 <li>Traits and metaclasses let you extend Moose's core attribute features</li>
3454 # perl bin/prove -lv t/06-advanced-attributes.t
3456 Iterate til this passes all its tests</pre>
3459 <div class="slide fake-slide0">
3460 <h1>Part 7: Introspection</h1>
3463 <div class="slide fake-slide0">
3464 <h1>Part 8: A Tour of MooseX</h1>
3467 <div class="slide fake-slide0">
3468 <h1>Part 9: Writing Moose Extensions</h1>
3471 <div class="slide fake-slide0">
3476 <h1>More Information</h1>
3479 <li><a href="http://moose.perl.org/">http://moose.perl.org/</a></li>
3480 <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>
3481 <li><a href="irc://irc.perl.org/#moose">irc://irc.perl.org/#moose</a></li>
3482 <li>mailing list - <a href="mailto:moose@perl.org">moose@perl.org</a></li>
3483 <li>Slides and exercises are in Moose's git repo:
3485 <span style="white-space: nowrap">git://jules.scsys.co.uk/gitmo/moose-presentations</span></li>
3495 Copyright 2009 David Rolsky. All Rights Reserved.
3497 This work is licensed under a Creative Commons Attribution-Share Alike
3498 3.0 United States License See
3499 http://creativecommons.org/licenses/by-sa/3.0/us/ for details.