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>
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>Mutability (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 );
240 'modify return values'
246 <h1>Type Constraints</h1>
249 <li>NOT A FULL-BLOWN TYPE SYSTEM!</li>
250 <li>But still darn useful</li>
251 <li>Constrain attribute values</li>
252 <li>Coerce from other types</li>
257 <h1>Type Constraint Example</h1>
259 <pre><code>package Person;
264 <span class="highlight">isa => 'Int'</span>,
268 Person->new( weight => 'fat' );</code></pre>
275 <li>Attributes can define delegations</li>
276 <li>Lets you hide some implementation details</li>
277 <li>Fewer objects to chase around</li>
284 <pre><code>package Person;
290 <span class="highlight">handles => { 'blog_host' => 'host' },</span>
293 <span class="highlight">$person->blog_host;</span>
294 # really calls $person->blog_uri->host</code></pre>
298 <h1>Constructors</h1>
301 <li>Moose creates <code>new()</code> for you</li>
302 <li>Provide an optional <code>BUIDARGS()</code> and <code>BUILD()</code></li>
310 <li>Provide an optional <code>DEMOLISH()</code></li>
315 <h1>Moose Meta-API</h1>
318 <li>Answers questions like ...
320 <li>What methods does this class have?</li>
321 <li>What are its parents?</li>
322 <li>What attributes does it have (including inherited attributes)?</li>
323 <li>What roles does it do?</li>
324 <li>Much, much, more</li>
331 <h1>Moose Meta-API</h1>
334 <li>Not just for introspection ...
336 <li>Add methods, attributes, roles, etc</li>
337 <li>Extend and alter core features</li>
347 <li>A quick bit of propaganda ...</li>
354 <pre><code>package Person;
357 has last_name => (
364 <h1>Without Moose</h1>
366 <pre class="small"><code>package Person;
376 if (exists $args{last_name}) {
377 confess "Attribute (last_name) does not pass the type constraint because: "
378 . "Validation failed for 'Str' with value $args{last_name}"
379 if ref($args{last_name});
380 $self->{last_nane} = $args{last_name};
383 return bless $self, $class;
391 confess "Attribute (last_name) does not pass the type constraint because: "
392 . "Validation failed for 'Str' with value $value"
394 $self->{last_name} = $value;
397 return $self->{last_name};
403 <h1>Side by side</h1>
405 <table class="side-by-side">
408 <pre><code>package Person;
411 has last_name => (
417 <pre class="small"><code>package Person;
427 if (exists $args{last_name}) {
428 confess "Attribute (last_name) does not pass the type constraint because: "
429 . "Validation failed for 'Str' with value $args{last_name}"
430 if ref($args{last_name});
431 $self->{last_nane} = $args{last_name};
434 return bless $self, $class;
442 confess "Attribute (last_name) does not pass the type constraint because: "
443 . "Validation failed for 'Str' with value $value"
445 $self->{last_name} = $value;
448 return $self->{last_name};
457 <h1>Side by side</h1>
459 <table class="side-by-side">
462 <pre><code><span class="match-moose">package Person;</span>
465 has last_name => (
471 <pre class="small"><code><span class="match-unsweet">package Person;</span>
481 if (exists $args{last_name}) {
482 confess "Attribute (last_name) does not pass the type constraint because: "
483 . "Validation failed for 'Str' with value $args{last_name}"
484 if ref($args{last_name});
485 $self->{last_nane} = $args{last_name};
488 return bless $self, $class;
496 confess "Attribute (last_name) does not pass the type constraint because: "
497 . "Validation failed for 'Str' with value $value"
499 $self->{last_name} = $value;
502 return $self->{last_name};
510 <h1>Side by side</h1>
512 <table class="side-by-side">
515 <pre><code>package Person;
516 <span class="match-moose">use Moose;</span>
518 has last_name => (
524 <pre class="small"><code>package Person;
525 <span class="match-unsweet">use strict;
532 my $self = {};</span>
534 if (exists $args{last_name}) {
535 confess "Attribute (last_name) does not pass the type constraint because: "
536 . "Validation failed for 'Str' with value $args{last_name}"
537 if ref($args{last_name});
538 $self->{last_nane} = $args{last_name};
541 <span class="match-unsweet">return bless $self, $class;
549 confess "Attribute (last_name) does not pass the type constraint because: "
550 . "Validation failed for 'Str' with value $value"
552 $self->{last_name} = $value;
555 return $self->{last_name};
563 <h1>Side by side</h1>
565 <table class="side-by-side">
568 <pre><code>package Person;
571 <span class="match-moose">has last_name => (</span>
574 <span class="match-moose">);</span></code></pre>
577 <pre class="small"><code>package Person;
587 <span class="match-unsweet">if (exists $args{last_name}) {</span>
588 confess "Attribute (last_name) does not pass the type constraint because: "
589 . "Validation failed for 'Str' with value $args{last_name}"
590 if ref($args{last_name});
591 <span class="match-unsweet">$self->{last_nane} = $args{last_name};
594 return bless $self, $class;
602 confess "Attribute (last_name) does not pass the type constraint because: "
603 . "Validation failed for 'Str' with value $value"
605 $self->{last_name} = $value;
608 return $self->{last_name};
616 <h1>Side by side</h1>
618 <table class="side-by-side">
621 <pre><code>package Person;
624 has last_name => (
625 <span class="match-moose">is => 'rw',</span>
630 <pre class="small"><code>package Person;
640 if (exists $args{last_name}) {
641 confess "Attribute (last_name) does not pass the type constraint because: "
642 . "Validation failed for 'Str' with value $args{last_name}"
643 if ref($args{last_name});
644 $self->{last_nane} = $args{last_name};
647 return bless $self, $class;
650 <span class="match-unsweet">sub last_name {
654 my $value = shift;</span>
655 confess "Attribute (last_name) does not pass the type constraint because: "
656 . "Validation failed for 'Str' with value $value"
658 <span class="match-unsweet">$self->{last_name} = $value;
661 return $self->{last_name};
662 }</span></code></pre>
669 <h1>Side by side</h1>
671 <table class="side-by-side">
674 <pre><code>package Person;
677 has last_name => (
679 <span class="match-moose">isa => 'Str',</span>
683 <pre class="small"><code>package Person;
693 if (exists $args{last_name}) {
694 <span class="match-unsweet">confess "Attribute (last_name) does not pass the type constraint because: "
695 . "Validation failed for 'Str' with value $args{last_name}"
696 if ref($args{last_name});</span>
697 $self->{last_nane} = $args{last_name};
700 return bless $self, $class;
708 <span class="match-unsweet">confess "Attribute (last_name) does not pass the type constraint because: "
709 . "Validation failed for 'Str' with value $value"
710 if ref($value);</span>
711 $self->{last_name} = $value;
714 return $self->{last_name};
722 <h1>Side by side</h1>
724 <table class="side-by-side">
725 <tr class="incremental">
729 <tr class="incremental">
730 <td>92 characters</td>
731 <td>741 characters</td>
735 <pre><code>package Person;
738 has last_name => (
744 <pre class="small"><code>package Person;
754 if (exists $args{last_name}) {
755 confess "Attribute (last_name) does not pass the type constraint because: "
756 . "Validation failed for 'Str' with value $args{last_name}"
757 if ref($args{last_name});
758 $self->{last_nane} = $args{last_name};
761 return bless $self, $class;
769 confess "Attribute (last_name) does not pass the type constraint because: "
770 . "Validation failed for 'Str' with value $value"
772 $self->{last_name} = $value;
775 return $self->{last_name};
785 <pre class="small"><code>sub new {
790 if (exists $args{last_name}) {
791 confess "Attribute (last_name) does not pass the type constraint because: "
792 . "Validation failed for 'Str' with value $args{last_name}"
793 if ref($args{last_name});
794 $self->{last_nane} = $args{last_name};
797 return bless $self, $class;
804 <pre class="small"><code>if (exists $args{last_name}) {
805 confess "Attribute (last_name) does not pass the type constraint because: "
806 . "Validation failed for 'Str' with value $args{last_name}"
807 if ref($args{last_name});
808 $self->{last_nane} = $args{last_name};
815 <code>$self->{last_nane} = $args{last_name};</code>
820 <code>$self->{last_na<span class="wrong">n</span>e}</code>
826 <pre><code>package Person;
829 has last_name => (
835 <div class="slide fake-slide0">
836 <h1>Part 1: Moose Classes</h1>
840 <h1>Moose Classes</h1>
843 <li>Moose classes are Perl packages which <code>use Moose</code></li>
848 <h1>Moose.pm and Your Class</h1>
850 <pre><code>package Person;
851 use Moose;</code></pre>
854 <li><code>Moose.pm</code> provides declarative sugar</li>
855 <li>Turns on <code>strict</code> and <code>warnings</code></li>
856 <li>Creates metaclasses for your class: <code>Person->meta</code></li>
857 <li>Moose classes automatically inherit from <code>Moose::Object</code></li>
862 <h1>What <code>Moose::Object</code> Provides</h1>
865 <li>Constructor - <code>new()</code></li>
866 <li>Calls your <code>BUILDARGS()</code> and/or <code>BUILD()</code></li>
867 <li>Calls your <code>DEMOLISH</code> during object destruction</li>
875 <li>Takes <code>@_</code>, returns a hash reference of attribute names/value</li>
876 <li>Accepts a hash or hashref; throws otherwise</li>
877 <li>Provide your own for other cases</li>
878 <li><strong>Always</strong> call <code>$class->SUPER::BUILDARGS(@_)</code> as a fallback!</li>
883 <h1>BUILDARGS Example</h1>
885 <pre><code>package Person;
891 if ( @_ == 1 && ! ref $_[0] ) {
892 <span class="highlight">return { ssn => $_[0] };</span>
894 <span class="highlight">return $class->SUPER::BUILDARGS(@_)</span>;
897 <span class="highlight">Person->new('123-45-6789')</span></code></pre>
904 <li>Called after object is created, before <code>new</code> returns</li>
905 <li>Chance to do more complex validation, set complex attributes</li>
906 <li>Called in reverse inheritance order, parents to children</li>
907 <li>Return value is ignored</li>
912 <h1>BUILD Example</h1>
914 <pre><code>package Person;
920 if ( $self->country_of_residence
922 die 'All US residents'
923 . ' must have an SSN'
924 unless $self->has_ssn;
930 <h1>Object Construction a la Moose</h1>
932 <pre><code>Person->new(@_)</code></pre>
935 <li>Calls <code>Person->BUILDARGS(@_)</code> to turn <code>@_</code> into a hashref</li>
936 <li>Blesses a reference</li>
937 <li>Populates attributes based on the hashref from #1</li>
938 <li>Calls <code>$new_object->BUILDALL($constructor_args)</code>
939 <br />... which calls all <code>BUILD</code> methods</li>
940 <li>Returns the object</li>
945 <h1>The Object is Opaque</h1>
948 <li>Technically it's a hash reference</li>
949 <li><span class="wrong">If you <em>ever</em> treat it as one <strong>you are doing it wrong!</strong></span></li>
957 <li>Like <code>DESTROY</code>, but Moose makes sure all <code>DEMOLISH</code> methods in a hierarchy are called</li>
958 <li>Called in normal inheritance order, children to parents</li>
966 <li><code>extends</code> is sugar for declaring parent classes</li>
969 <pre><code>package Employee;
971 <span class="highlight">extends 'Person';</span></code></pre>
978 <li>Each call to <code>extends</code> <strong>resets</strong> your parents</li>
981 <h2 class="wrong">Wrong</h2>
983 <pre><code>package EvilEmployee;
986 extends 'Thief';</code></pre>
988 <h2 class="right">Right</h2>
990 <pre><code>package EvilEmployee;
992 extends 'Person', 'Thief';</code></pre>
996 <h1>Extending un-Moose-y Parents</h1>
998 <pre><code>package My::LWP;
1000 extends 'LWP';</code></pre>
1003 <li>No <code>Moose::Object</code>, so ...
1005 <li>No attribute-handling <code>new()</code></li>
1006 <li>No <code>BUILDARGS()</code> or <code>BUILD()</code></li>
1007 <li>No <code>DEMOLISH()</code></li>
1010 <li>But see <code>MooseX::NonMoose</code> for a workaround</li>
1015 <h1><code>override</code> and <code>super</code></h1>
1018 <li><code>override</code> is another method modifier</li>
1019 <li>An alternative to Perl's <code>SUPER::</code></li>
1024 <h1><code>override</code> and <code>super</code></h1>
1026 <pre><code>package Employee;
1029 <span class="current incremental">extends 'Person';</span>
1031 <span class="incremental">override</span> work => sub {
1035 unless $self->got_paid;
1036 <span class="incremental">super();</span>
1037 }<span class="incremental">;</span></code></pre>
1041 <h1>Caveat <code>super</code></h1>
1044 <li>Mostly like <code>$self->SUPER::work(@_)</code></li>
1045 <li><strong>But</strong> cannot change <code>@_</code>!</li>
1046 <li>Binds the parent's method at compile time</li>
1051 <h1>Minimal Attributes</h1>
1054 <li><code>has 'foo'</code></li>
1055 <li>Use <code>is => 'ro'</code> or <code>is => 'rw'</code></li>
1056 <li>Attributes without "is" have no accessors</li>
1061 <h1>Read-write attributes</h1>
1063 <pre><code>package Person;
1066 has first_name => ( <span class="highlight">is => 'rw'</span> );
1069 Person->new( first_name => 'Dave' );
1071 $person->first_name('Stevan');
1072 print $person->first_name; # Stevan</code></pre>
1077 <h1>Read-only attributes</h1>
1079 <pre><code>package Person;
1082 has first_name => ( <span class="highlight">is => 'ro'</span> );
1085 Person->new( first_name => 'Dave' );
1087 $person->first_name('Stevan');
1088 print $person->first_name; # Dave</code></pre>
1093 <h1>There is More to Come</h1>
1096 <li>Attributes have a <em>lot</em> of features</li>
1101 <h1>Cleaning Up Moose Droppings</h1>
1103 <pre><code>package Person;
1107 Person->can('extends');</code></pre>
1110 <li>Not very hygienic</li>
1115 <h1>Cleaning Up Moose Droppings</h1>
1117 <pre><code>package Person;
1125 Person->can('extends');</code></pre>
1132 <li><code>no Moose</code> at the end of a package is a best practice</li>
1133 <li>Or <code>use namespace::autoclean</code> at the top</li>
1139 <h1>Immutability</h1>
1142 <li><span style="font-family: URW Chancery L; font-size: 140%">Stevan's Incantation of Fleet-Footedness</span></li>
1145 <pre><code>package Person;
1148 <span class="highlight">__PACKAGE__->meta->make_immutable;</span></code></pre>
1152 <h1>What <code>make_immutable</code> does</h1>
1156 <li>Uses <code>eval</code> to "inline" a constructor</li>
1157 <li>Memoizes a lot of meta-information</li>
1158 <li>Makes loading your class slower</li>
1159 <li>Makes object creation <em>much</em> faster</li>
1164 <h1>When to Immutabilize?</h1>
1167 <li><em>Almost</em> always</li>
1168 <li>Startup time vs execution time</li>
1173 <h1>Classes Summary</h1>
1176 <li><code>use Moose</code></li>
1177 <li><code>Class->meta</code></li>
1178 <li><code>Moose::Object</code> base class</li>
1179 <li><code>extends</code>, <code>override</code>, and <code>super</code></li>
1180 <li>Simple attributes: <code>has</code>, <code>is => 'ro'</code>, & <code>is => 'rw'</code></li>
1181 <li><code>no Moose</code></li>
1182 <li><code>__PACKAGE__->meta->make_immutable</code></li>
1195 # perl bin/prove -lv t/00-prereq.t
1197 # perl install-moose (if needed)
1199 # perl bin/prove -lv t/01-classes.t
1201 Iterate til this passes all its tests</pre>
1204 <div class="slide fake-slide0">
1205 <h1>Part 2: Roles</h1>
1209 <h1>Just What Is a Role?</h1>
1212 <li>Mixin? Interface? Trait?</li>
1213 <li>Yes ... and more!</li>
1218 <h1>Roles - State <strong>and</strong> Behavior</h1>
1220 <pre><code>package HasPermissions;
1222 <span class="current incremental"># state
1223 has access_level => ( is => 'rw' );</span>
1225 <span class="incremental"># behavior
1228 my $required = shift;
1230 return $self->access_level
1232 }</span></code></pre>
1237 <h1>Roles Can Define Interfaces</h1>
1239 <pre><code>package Printable;
1242 requires 'as_string';</code></pre>
1246 <h1>Roles Can Do All Three</h1>
1248 <pre><code>package Printable;
1251 requires 'as_string';
1253 has has_been_printed => ( is => 'rw' );
1257 print $self->as_string;
1258 $self->has_been_printed(1);
1263 <h1>Classes Consume Roles</h1>
1265 <pre><code>package Person;
1268 with 'HasPermissions';</code></pre>
1272 <h1>Classes Consume Roles</h1>
1274 <pre><code>my $person = Person->new(
1275 first_name => 'Kenichi',
1276 last_name => 'Asai',
1277 access_level => 42,
1280 print $person->full_name
1282 . $person->can_access(42)
1284 : 'little power';</code></pre>
1288 <h1>Roles in Practice</h1>
1291 <li>Consuming a role =~ inlining the role</li>
1296 <h1>In Other Words ...</h1>
1298 <pre><code>package Person;
1301 <span class="highlight">with 'Printable';</span></code></pre>
1305 <h1>In Other Words ...</h1>
1307 <pre><code>package Person;
1310 <span class="delete">with 'Printable';</span>
1312 <span class="highlight">has has_been_printed => ( is => 'rw' );
1316 print $self->as_string;
1317 $self->has_been_printed(1);
1318 }</span></code></pre>
1325 <li>Role consumption is introspectable</li>
1328 <pre><code>if ( Person->does('Printable') ) { ... }
1332 Person->meta->does('Printable')</code></pre>
1337 <h1>These Names Are the Same</h1>
1340 <li>What if a role and class define the same method?</li>
1341 <li>A class's <em>local</em> methods win over the role's</li>
1342 <li>The role's methods win over the class's <em>inherited</em> methods</li>
1347 <h1>Conflicts Between Roles</h1>
1350 <li>Two roles with a method of the same name</li>
1351 <li>Generates a compile-time error when consumed by a class</li>
1356 <h1>Conflict Example</h1>
1358 <pre><code>package IsFragile;
1363 package CanBreakdance;
1366 sub break { ... }</code></pre>
1370 <h1>Conflict Example</h1>
1372 <pre><code>package FragileDancer;
1375 <span class="highlight">with 'IsFragile', 'CanBreakdance';</span></code></pre>
1378 <li>Only one <code>with</code>!</li>
1383 <h1>Conflict Resolution</h1>
1386 <li>The consuming class must resolve the conflict by implementing the method</li>
1387 <li>Can use some combination of method exclusion and aliasing</li>
1392 <h1>Method Aliasing</h1>
1394 <pre><code>package FragileDancer;
1397 <span class="highlight">with 'IsFragile' =>
1399 { break => 'break_bone' } },
1402 { break => 'break_it_down' } };</span></code></pre>
1405 <li>Renames the roles' methods</li>
1406 <li>Still conflicts, need to <code>exclude</code> as well</li>
1411 <h1>Method Exclusion</h1>
1413 <pre><code>package FragileDancer;
1416 <span class="highlight">with 'IsFragile' =>
1418 { break => 'break_bone' },
1419 -excludes => 'break' },
1422 { break => 'break_dance' },
1423 -excludes => 'break' };</span></code></pre>
1427 <h1>And then ...</h1>
1429 <pre><code>package FragileDancer;
1436 if ( rand(1) < 0.5 ) {
1443 <h1>Still Full of Fail</h1>
1446 <li>Roles are also about semantics!</li>
1447 <li>We've fulfilled the letter and lost the spirit</li>
1448 <li>Roles have a <em>meaning</em></li>
1449 <li>Think twice before blindly aliasing and excluding methods!</li>
1454 <h1>Hot Role-on-Role Action</h1>
1456 <pre><code>package Comparable;
1459 requires 'compare';</code></pre>
1463 <h1>Hot Role-on-Role Action</h1>
1465 <pre><code>package TestsEquality;
1472 return $self->compare(@_) == 0;
1477 <h1>And then ...</h1>
1479 <pre><code>package Integer;
1482 with 'TestsEquality';
1484 # Satisfies the Comparable role
1487 Integer->does('TestsEquality'); # true
1488 Integer->does('Comparable'); # also true!</code></pre>
1492 <h1>Name Conflicts Between Roles</h1>
1494 <pre><code>package HasSubProcess;
1497 <span class="highlight">sub execute { ... }</span>
1502 with 'HasSubProcess';
1504 <span class="highlight">sub execute { ... }</span></code></pre>
1508 <h1>Delayed Conflict</h1>
1510 <pre><code>package StateOfTexas;
1511 with 'Killer';</code></pre>
1514 <li><code>StateOfTexas</code> must implement its own <code>execute</code></li>
1515 <li>But loading the <code>Killer</code> role by itself does not cause an error</li>
1520 <h1>Roles as Interfaces</h1>
1523 <li>Roles can <code>require</code> methods of their consumers</li>
1524 <li>Compile-time checks</li>
1525 <li>Method must exist when the role is consumed</li>
1530 <h1>The Attribute Gotcha</h1>
1532 <pre><code>package HasSize;
1535 <span class="current incremental">requires 'size';</span>
1540 <span class="incremental">with 'HasSize';
1542 has size => ( is => 'ro' );</span></code></pre>
1546 <h1>The Attribute Gotcha Workaround</h1>
1548 <pre><code>package HasSize;
1556 has size => ( is => 'ro' );
1558 with 'HasSize';</code></pre>
1562 <h1>Compile-time Is a Lie</h1>
1565 <li>Really, it's <em>package load</em> time</li>
1566 <li>That's run-time, but before the "real" run-time</li>
1567 <li>Moose does not rewire Perl, it's just sugar!</li>
1568 <li>(but <code>MooseX::Declare</code> <em>does</em> rewire Perl)</li>
1573 <h1>Enforcing Roles</h1>
1575 <pre><code>package Comparison;
1578 has [ 'left', 'right' ] => (
1580 <span class="highlight">does => 'Comparable',</span>
1585 <li>A sneak peek at type constraints</li>
1591 <h1>Roles Can Be Applied to Objects</h1>
1593 <pre><code>use Moose::Util qw( apply_all_roles );
1595 my $fragile_person = Person->new( ... );
1596 apply_all_roles( $fragile_person,
1597 'IsFragile' );</code></pre>
1600 <li>Does not change the <code>Person</code> class</li>
1601 <li>Works with non-Moose classes, great for monkey-patching!</li>
1606 <h1>Roles Are Dirty Too</h1>
1609 <li>Once again, clean up those Moose droppings</li>
1612 <pre><code>package Comparable;
1617 <span class="highlight">no Moose::Role;</span></code></pre>
1620 <li>But roles cannot be made immutable</li>
1625 <h1>The Zen of Roles</h1>
1628 <li>Roles represent discrete units of ...
1635 <li>Roles are shareable between unrelated classes</li>
1636 <li>Roles are what a class <em>does</em>, not what it <em>is</em></li>
1637 <li>Roles <em>add</em> functionality, inheritance <em>specializes</em></li>
1642 <h1>Abstract Examples</h1>
1645 <li>Human <em>@ISA</em> Animal</li>
1646 <li>Human <em>does</em> Toolmaker (as <em>does</em> Chimpanzee)</li>
1647 <li>Car <em>@ISA</em> Vehicle</li>
1648 <li>Car <em>does</em> HasEngine</li>
1653 <h1>Real Examples</h1>
1656 <li>Objects representing SQL database components and queries
1658 <li>Schema, Table, Column, ColumnAlias</li>
1659 <li>Select, Insert, Update, Delete</li>
1666 <h1>Real Examples</h1>
1669 <li>Column and ColumnAlias both <em>do</em> ColumnLike</li>
1670 <li>ColumnLike things can be used in certain parts of queries</li>
1671 <li>All queries <em>do</em> HasWhereClause</li>
1672 <li>Select <em>does</em> Comparable and Selectable (for subselects)</li>
1673 <li>A where clause requires its components to <em>do</em> Comparable</li>
1678 <h1>Roles Summary</h1>
1681 <li>Roles can define an interface with <code>requires</code></li>
1682 <li>Roles can have state (attributes) and behavior (methods)</li>
1683 <li>Roles can mix interface, state, & behavior</li>
1684 <li>Roles are composed (flattened) into classes</li>
1685 <li>Roles can do other roles</li>
1686 <li>Roles can be used as a type in APIs (must do Comparable)</li>
1698 # perl bin/prove -lv t/02-roles.t
1700 Iterate til this passes all its tests</pre>
1703 <div class="slide fake-slide0">
1704 <h1>Part 3: Basic Attributes</h1>
1708 <h1>Attributes Are Huge</h1>
1711 <li>Moose's biggest feature</li>
1712 <li>The target of <em>many</em> MooseX modules</li>
1717 <h1>Quick Review</h1>
1720 <li>Declared with <code>has</code></li>
1721 <li>Read-only or read-write</li>
1724 <pre><code>package Shirt;
1727 has 'color' => ( is => 'ro' );
1728 has 'is_ripped' => ( is => 'rw' );</code></pre>
1732 <h1>Required-ness</h1>
1735 <li>Required means "must be passed to the constructor"</li>
1736 <li>But can be <code>undef</code></li>
1741 <h1>Required-ness</h1>
1743 <pre><code>package Person;
1746 has first_name => (
1748 <span class="current incremental">required => 1,</span>
1751 <span class="incremental">Person->new( first_name => undef ); # ok
1752 Person->new(); # kaboom</span></code></pre>
1756 <h1>Default and Builder</h1>
1759 <li>Attributes can have defaults</li>
1760 <li>Simple non-referecne scalars (number, string)</li>
1761 <li>Subroutine reference</li>
1762 <li>A builder method</li>
1770 <li>Can be a non-reference scalar (including <code>undef</code>)</li>
1773 <pre><code>package Person;
1778 default => 'Spire FCU',
1786 <li>Can be a subroutine reference</li>
1789 <pre><code>package Person;
1796 name => 'Spire FCU' ) },
1801 <h1>Subroutine Reference Default</h1>
1804 <li>Called as a method on the object</li>
1805 <li>Called anew for each object</li>
1810 <h1>Why No Other Reference Types?</h1>
1812 <pre><code>package Person;
1817 <span class="wrong">default => Bank->new(
1818 name => 'Spire FCU' ),</span>
1822 <li>Now <strong>every</strong> person shares the <strong>same</strong> Bank object!</li>
1827 <h1>Defaulting to an Empty Reference</h1>
1829 <pre><code>package Person;
1832 has packages => (
1834 default => <span class="highlight">sub { [] }</span>,
1839 <h1>What if I Want to Share?</h1>
1841 <pre><code>package Person;
1844 my $highlander_bank =
1845 Bank->new( name => 'Spire FCU' );
1849 default => sub { $highlander_bank },
1857 <li>A method <em>name</em> which returns the default</li>
1864 <pre><code>package Person;
1869 builder => '_build_bank',
1874 return Bank->new(
1875 name => 'Spire FCU' );
1880 <h1>Default vs Builder</h1>
1883 <li>Use default for simple scalars</li>
1884 <li>Use default to return empty references</li>
1885 <li>Use default for <em>very</em> trivial subroutine references</li>
1886 <li>Use builder for everything else</li>
1891 <h1>Builder Bonuses</h1>
1894 <li>Can be overridden and method modified, because it's called by <em>name</em></li>
1895 <li>Roles can require a builder</li>
1900 <h1>Role Requires Builder</h1>
1902 <pre><code>package HasBank;
1905 requires '_build_bank';
1909 builder => '_build_bank',
1914 <h1>Lazy, Good for Nothin' Attributes</h1>
1917 <li>Normally, defaults are generated during object construction</li>
1918 <li>This can be expensive</li>
1919 <li>We want to default to <code>$self->size * 2</code>, but attribute initialization order is unpredictable</li>
1920 <li>Use lazy attributes!</li>
1925 <h1>The Power of Dynamic Defaults</h1>
1927 <pre><code>package Person;
1930 has shoe_size => (
1936 <h1>The Power of Dynamic Defaults</h1>
1938 <pre><code>has shoes => (
1940 <span class="highlight">lazy => 1,</span>
1941 builder => '_build_shoes',
1947 return Shoes->new(
1948 size => <span class="highlight">$self->shoe_size</span> );
1953 <h1>Lazy is Good</h1>
1956 <li>Lazy defaults are executed when the attribute is read</li>
1957 <li>Can see other object attributes</li>
1958 <li>Still need to watch out for circular laziness</li>
1963 <h1>Clearer and Predicate</h1>
1966 <li>Attributes can have a value, including <code>undef</code>, or not</li>
1967 <li>Can clear the value with a clearer method</li>
1968 <li>Can check for the existence of a value with a predicate method</li>
1969 <li>By default, these methods are not created</li>
1974 <h1>Clearer and Predicate</h1>
1976 <pre><code>package Person;
1982 builder => '_build_account',
1983 <span class="highlight">clearer => '_clear_account',
1984 predicate => 'has_account',</span>
1989 <h1>Clearer and Lazy Defaults</h1>
1992 <li>Lazy defaults are good for computed attributes</li>
1993 <li>Clear the attribute when the source data changes</li>
1994 <li>Recalculated at next access</li>
1999 <h1>Renaming constructor arguments</h1>
2002 <li>By default, constructor names = attribute names</li>
2003 <li>Use <code>init_arg</code> to change this</li>
2004 <li>Set <code>init_arg => undef</code> to make it unconstructable</li>
2009 <h1>Some <code>init_arg</code> examples</h1>
2011 <pre><code>package Person;
2016 <span class="highlight">init_arg => 'foot_size',</span>
2019 Person->new( <span class="wrong">shoe_size => 13</span> );
2022 Person->new( <span class="right">foot_size => 13</span> );
2023 print $person->shoe_size;</code></pre>
2027 <h1>Some <code>init_arg</code> examples</h1>
2029 <pre><code>package Person;
2034 <span class="highlight">init_arg => undef,</span>
2037 Person->new( <span class="wrong">shoes => Shoes->new</span> );</code></pre>
2041 <h1>Why Set <code>init_arg => undef</code>?</h1>
2044 <li>Use this with a lazy default for attributes-as-cache</li>
2045 <li>Compute the value as needed</li>
2046 <li>Ensure that it is always generated correctly (not set by constructor)</li>
2047 <li>Use triggers or method modifiers (coming soon) to clear the value</li>
2052 <h1>Attribute Inheritance</h1>
2055 <li>By default, subclasses inherit attribute as-is</li>
2056 <li>Can change some attribute parameters in subclasses
2062 <li>others we've not yet covered</li>
2069 <h1>Attribute Inheritance Example</h1>
2071 <pre><code>package Employee;
2076 has '<span class="highlight">+first_name</span>' => (
2077 default => 'Joe',
2082 <h1>Attribute Inheritance Warning</h1>
2085 <li>An attribute is a contract about a class's API</li>
2086 <li>Don't break that contract in a subclass</li>
2087 <li>Especially important in the context of types</li>
2092 <h1>Changing Accessor Names</h1>
2094 <pre><code>package Person;
2097 has first_name => (
2098 <span class="highlight">accessor</span> => 'first_name',
2102 <li>The long-hand version of <code>is => 'rw'</code></li>
2107 <h1>Changing Accessor Names</h1>
2109 <pre><code>package Person;
2112 has first_name => (
2113 <span class="highlight">reader</span> => 'first_name',
2114 <span class="highlight">writer</span> => undef,
2118 <li>The long-hand version of <code>is => 'ro'</code></li>
2124 <h1>Changing Accessor Names</h1>
2126 <pre><code>package Person;
2129 has first_name => (
2130 <span class="highlight">reader</span> => 'get_first_name',
2131 <span class="highlight">writer</span> => 'set_first_name',
2136 <h1>Changing Accessor Names</h1>
2138 <pre><code>package Person;
2141 has first_name => (
2142 <span class="highlight">is</span> => 'rw',
2143 <span class="highlight">writer</span> => '_first_name',
2147 <li>Can also mix-and-match <code>is</code> and explicit names</li>
2152 <h1>ETOOMUCHTYPING</h1>
2155 <li><code>MooseX::FollowPBP</code><br /><code>get_foo</code> and <code>set_foo</code></li>
2156 <li><code>MooseX::SemiAffordanceAccessor</code><br /><code>foo</code> and <code>set_foo</code></li>
2161 <h1>ETOOMUCHTYPING</h1>
2163 <pre><code>package Person;
2165 <span class="highlight">use MooseX::SemiAffordanceAccessor;</span>
2167 has first_name => (
2172 <li>Creates <code>first_name</code> and <code>set_first_name</code></li>
2177 <h1>Basic Attributes Summary</h1>
2180 <li>Attributes can be <code>required</code></li>
2181 <li>Attributes can have a <code>default</code> or <code>builder</code></li>
2182 <li>Attributes with a default or builder can be <code>lazy</code></li>
2183 <li>Attributes can have a <code>clearer</code> and/or <code>predicate</code></li>
2184 <li>An attribute's constructor name can be changed with <code>init_arg</code></li>
2185 <li>A subclass can alter its parents' attributes</li>
2186 <li>Attribute accessor names can be changed</li>
2198 # perl bin/prove -lv \
2199 t/03-basic-attributes.t
2201 Iterate til this passes all its tests</pre>
2204 <div class="slide fake-slide0">
2205 <h1>Part 4: Method Modifiers</h1>
2209 <h1>What is a Method Modifier</h1>
2212 <li>Apply to an existing method</li>
2213 <li>... from a parent class, the current class, or a role</li>
2214 <li>Roles can provide modifiers that are applied at composition time</li>
2219 <h1>What is a Method Modifier</h1>
2222 <li>"Inject" behavior</li>
2223 <li>Add behavior to generated methods (accessors, delegations)</li>
2224 <li>Provide roles which modify existing behavior</li>
2229 <h1>Before and After</h1>
2232 <li>Simplest modifiers - <code>before</code> and <code>after</code></li>
2233 <li>Guess when they run!</li>
2238 <h1>Uses for <code>before</code></h1>
2241 <li>As a pre-call check</li>
2244 <pre><code>package Person;
2247 before work => sub {
2249 die 'I have no job!'
2250 unless $self->has_title;
2255 <h1>Uses for <code>before</code></h1>
2258 <li>Logging/Debugging</li>
2261 <pre><code>package Person;
2264 before work => sub {
2266 return unless $DEBUG;
2268 warn "Called work on ",
2269 $self->full_name,
2270 "with the arguments: [@_]\n";
2275 <h1>Uses for <code>after</code></h1>
2278 <li>Also works for logging/debugging</li>
2279 <li>Post-X side-effects (recording audit info)</li>
2282 <pre><code>package Person;
2285 after work => sub {
2287 $self->work_count(
2288 $self->work_count + 1 );
2296 <li>Modifiers are useful for adding behavior to generated methods</li>
2301 <h1>More Modifier Examples</h1>
2303 <pre><code>has password => (
2305 clearer => 'clear_password',
2307 has hashed_password => (
2309 builder => '_build_hashed_password',
2310 clearer => '_clear_hashed_password',
2312 after clear_password => sub {
2314 $self->_clear_hashed_password;
2319 <h1><code>before</code> and <code>after</code> Limitations</h1>
2322 <li>Cannot alter method parameters</li>
2323 <li>Cannot alter return value</li>
2324 <li>But <strong>can</strong> throw an exception</li>
2329 <h1>The <code>around</code> Modifier</h1>
2332 <li>The big gun</li>
2333 <li>Can alter parameters <strong>and/or</strong> return values</li>
2334 <li>Can skip calling the wrapped method entirely</li>
2339 <h1>The power of <code>around</code></h1>
2341 <pre><code>around insert => sub {
2345 $self->_validate_insert(@_);
2349 $self->_munge_insert(@_) );
2351 $new_user->_assign_uri;
2357 <h1>Modifier Order</h1>
2360 <li>Before runs order from last to first</li>
2361 <li>After runs in order from first to last</li>
2362 <li>Around runs in order from last to first</li>
2367 <h1>Modifier Order Illustrated</h1>
2370 <span class="current incremental">before 2
2372 <span class="incremental">around 2
2374 <span class="incremental">wrapped method</span>
2375 <span class="incremental">around 1
2377 <span class="incremental">after 1
2383 <h1>Modifiers in Roles</h1>
2386 <li>Roles can use these modifiers</li>
2387 <li>Very powerful!</li>
2392 <h1>Modifiers in Roles</h1>
2394 <pre><code>package IsUnreliable;
2397 <span class="highlight">requires 'run';
2399 around run</span> => sub {
2403 return if rand(1) < 0.5;
2405 return $self->$orig(@_);
2410 <h1>Augment and Inner</h1>
2413 <li>Inverted <code>super</code></li>
2414 <li>From least- to most-specific</li>
2415 <li>Grandparent to parent to child</li>
2416 <li>Not allowed in roles</li>
2421 <h1>Augment and Inner</h1>
2423 <pre><code>package Document;
2425 sub xml { '<doc>' . <span class="highlight">inner()</span> . '</doc>' }
2429 <span class="highlight">augment xml</span> =>
2430 sub { title() . <span class="highlight">inner()</span> . summary() };
2434 <span class="highlight">augment xml</span> =>
2435 sub { tps_xml() . <span class="highlight">inner()</span> };</code></pre>
2439 <h1>Augment and Inner</h1>
2442 <li>When we call <code>$tps->xml</code> ...
2444 <li><code>Document->xml</code></li>
2445 <li><code>Report->xml</code></li>
2446 <li><code>TPSReport->xml</code></li>
2453 <h1>Augment and Inner Usage</h1>
2456 <li>Call <code>inner()</code> to "fill in the blank"</li>
2457 <li>Requires designing for subclassing</li>
2458 <li>Call <code>inner()</code> in the terminal class, just in case</li>
2463 <h1>Method Modifiers Summary</h1>
2466 <li>Use <code>before</code> and <code>after</code> for ...
2469 <li>pre- or post-validation</li>
2470 <li>to add behavior to generated methods</li>
2473 <li>These two modifiers cannot change parameters or return values</li>
2478 <h1>Method Modifiers Summary</h1>
2481 <li>Use <code>around</code> to ...
2483 <li>alter parameters passed to the original method</li>
2484 <li>alter the return value of the original method</li>
2485 <li>not call the original method at all (or call a <em>different</em> method)</li>
2492 <h1>Method Modifiers Summary</h1>
2495 <li>When using modifiers in a role, require the modified method</li>
2496 <li>Use <code>augment</code> and <code>inner</code> to invert the normal subclassing flow ...
2498 <li>Least- to most-specific (parents to children)</li>
2499 <li>Build in "insertability" (stick more stuff in the "middle")</li>
2502 <li>Always call <code>inner</code> in the most specific subclass to allow for future extension</li>
2514 # perl bin/prove -lv \
2515 t/04-method-modifiers.t
2517 Iterate til this passes all its tests</pre>
2520 <div class="slide fake-slide0">
2521 <h1>Part 5: Types</h1>
2525 <h1>A Type System for Perl</h1>
2528 <li>Sort of ...</li>
2529 <li><em>Variables</em> are not typed</li>
2530 <li>Attributes can have types</li>
2531 <li>MooseX modules let you define method signatures</li>
2536 <h1>Components of a Moose Type</h1>
2539 <li>A type is a name and a constraint</li>
2540 <li>Types have a hierarchy</li>
2541 <li>Constraints are cumulative from parents</li>
2542 <li>Types can have associated coercions</li>
2547 <h1>Built-in Type Hierarchy</h1>
2566 <h1>Built-in Type Hierarchy</h1>
2599 <li>Like Perl's <code>if ($foo)</code></li>
2604 <h1>Value (and subtypes)</h1>
2607 <li><code>Value</code> is true when <code>! ref $thing</code></li>
2608 <li><code>Value</code> and <code>Str</code> are effectively the same, but <code>Str</code> is more expressive</li>
2609 <li>An overloaded object which numifies does not pass the <code>Num</code> constraint!</li>
2610 <li>Perl 5's overloading is hopelessly broken</li>
2615 <h1>ClassName and RoleName</h1>
2618 <li>A string with a package name</li>
2619 <li>The package <strong>must already be loaded</strong></li>
2624 <h1>Parameterizable Types</h1>
2627 <li>What does <code>ArrayRef[`a]</code> mean?</li>
2628 <li><code>s/`a/Int/</code> (or <code>Str</code> or ...)</li>
2629 <li>When you use it you can write ...
2631 <li><code>ArrayRef</code> (== <code>ArrayRef[Item]</code>)</li>
2632 <li><code>ArrayRef[Str]</code></li>
2633 <li><code>ArrayRef[MyTypeName]</code></li>
2634 <li><code>ArrayRef[HashRef[Maybe[Int]]]</code></li>
2644 <li>Maybe means either the named type or <code>undef</code></li>
2645 <li><code>Maybe[Int]</code> accepts integers or <code>undef</code></li>
2653 <li>This or that (or that or ...)</li>
2654 <li><code>Int | ArrayRef[Int]</code></li>
2655 <li>But use a coercion instead when possible</li>
2656 <li>Or use a <code>role_type</code>, <code>duck_type</code>, or anything not a union</li>
2657 <li>A union is often a code smell</li>
2662 <h1>Making Your Own Types</h1>
2664 <pre><code>use Moose::Util::TypeConstraints;
2666 <span class="incremental current">subtype 'PositiveInt',</span>
2667 <span class="incremental">as 'Int',</span>
2668 <span class="incremental">where { $_ > 0 },</span>
2669 <span class="incremental">message
2670 { "The value you provided ($_)"
2671 . " was not a positive int." };</span>
2675 <span class="incremental">isa => 'PositiveInt',</span>
2680 <h1>Automatic Types</h1>
2683 <li>Moose creates a type for every Moose class and role</li>
2684 <li>Unknown names are assumed to be classes</li>
2689 <h1>Automatic Types</h1>
2691 <pre><code>package Employee;
2696 <span class="highlight">isa => 'Employee',</span>
2699 has start_date => (
2701 <span class="highlight">isa => 'DateTime',</span>
2706 <h1>Subtype Shortcuts - <code>class_type</code></h1>
2708 <pre><code>use Moose::Util::TypeConstraints;
2709 class_type 'DateTime';
2713 where { $_->isa('DateTime') },
2714 message { ... };</code></pre>
2718 <h1>Subtype Shortcuts - <code>role_type</code></h1>
2720 <pre><code>use Moose::Util::TypeConstraints;
2721 role_type 'Printable';
2723 subtype 'Printable',
2726 { Moose::Util::does_role(
2727 $_, 'Printable' ) },
2728 message { ... };</code></pre>
2732 <h1>Subtype Shortcuts - <code>duck_type</code></h1>
2734 <pre><code>use Moose::Util::TypeConstraints;
2735 duck_type Car => qw( run break_down );
2739 where { all { $_->can($_) }
2740 qw( run break_down ) },
2741 message { ... };</code></pre>
2745 <h1>Subtype Shortcuts - <code>enum</code></h1>
2747 <pre><code>use Moose::Util::TypeConstraints;
2748 enum Color => qw( red blue green ) );
2750 my %ok = map { $_ => 1 }
2751 qw( red blue green );
2756 message { ... };</code></pre>
2760 <h1>Anonymous Subtypes</h1>
2762 <pre><code>package Person;
2764 <span class="highlight">my $posint =
2765 subtype as 'Int', where { $_ > 0 };</span>
2769 <span class="highlight">isa => $posint,</span>
2773 <li>Shortcuts have anonymous forms as well</li>
2780 <pre><code>use Moose::Util::TypeConstraints;
2784 where { ! /[a-z]/ };</code></pre>
2790 <pre><code><span class="incremental current">coerce 'UCStr',</span>
2791 <span class="incremental">from 'Str',</span>
2792 <span class="incremental">via { uc };</span>
2794 has shouty_name => (
2797 <span class="incremental">coerce => 1,</span>
2802 <h1>Coercion Examples</h1>
2804 <pre><code>subtype 'My::DateTime',
2805 as class_type 'DateTime';
2807 coerce 'My::DateTime',
2809 via { DateTime->new( %{$_} ) };
2811 coerce 'My::DateTime',
2813 via { DateTime->from_epoch(
2814 epoch => $_ ) };</code></pre>
2817 <li>Use coercion to inflate a value</li>
2822 <h1>Coercion Examples</h1>
2824 <pre><code>coerce 'ArrayRef[Int]',
2826 via { [ $_ ] };</code></pre>
2829 <li>Coerce instead of a union like <code style="white-space: nowrap">Int | ArrayRef[Int]</code></li>
2834 <h1>Using Types with Attributes</h1>
2836 <pre><code>package Person;
2840 <span class="highlight">isa => 'Num',</span>
2843 has favorite_numbers => (
2845 <span class="highlight">isa => 'ArrayRef[Int]',
2846 coerce => 1,</span>
2851 <h1>More Droppings</h1>
2854 <li><code>Moose::Util::TypeConstraint</code> also needs cleanup</li>
2857 <pre><code>package Person;
2860 use Moose::Util::TypeConstraints;
2865 <span class="highlight">no Moose::Util::TypeConstraints;</span></code></pre>
2869 <h1>Typed Methods (Low-tech)</h1>
2871 <pre class="medium"><code>package Person;
2872 <span class="highlight">use MooseX::Params::Validate qw( validated_list );</span>
2876 <span class="highlight">my ( $tasks, $can_rest ) =
2880 { isa => 'ArrayRef[Task]',
2891 <h1>Typed Methods (High-tech)</h1>
2893 <pre class="medium"><code>package Person;
2895 <span class="highlight">use MooseX::Method::Signatures;</span>
2897 <span class="highlight">method work ( ArrayRef[Task] :$tasks,
2898 Bool :$can_rest = 0 )</span> {
2906 <h1>Digression: The Type Registry</h1>
2909 <li>Types are actually <code>Moose::Meta::TypeConstraint</code> <em>objects</em></li>
2910 <li>Stored in an interpreter-global registry mapping names to objects</li>
2918 <li>Coercions are attached to type objects</li>
2919 <li>Therefore also global</li>
2920 <li>Name conflicts between modules!</li>
2921 <li>Coercion conflicts between modules!</li>
2926 <h1>Namespace Fix</h1>
2929 <li>Use some sort of pseudo-namespacing scheme</li>
2930 <li>Never coerce directly to a class name, or <em>to</em> built-in types</li>
2935 <h1>Namespace Fix</h1>
2937 <pre><code>use Moose::Util::TypeConstraints;
2938 subtype <span class="highlight">'MyApp::Type::DateTime',</span>
2941 <span class="highlight">coerce 'MyApp::Type::DateTime',</span>
2943 via { DateTime->new( %{$_} ) }
2945 has creation_date => (
2947 <span class="highlight">isa => 'MyApp::Type::DateTime',</span>
2953 <h1>Namespace Fix</h1>
2955 <pre><code>subtype 'MyApp::Type::ArrayOfInt',
2958 coerce 'MyApp::Type::ArrayOfInt',
2960 via { [ $_ ] };</code></pre>
2964 <h1>Namespace Fix Pros and Cons</h1>
2967 <li><span class="right">Relatively simple</span></li>
2968 <li><span class="right">Already built into Moose</span></li>
2969 <li><span class="wrong">Conflates type and module namespaces</span></li>
2970 <li><span class="wrong">Type names are strings, so typos are easy to make and may be hard to find</span></li>
2975 <h1>MooseX::Types</h1>
2977 <pre><code>package MyApp::Types;
2980 <span class="highlight">-declare => [ qw( ArrayOfInt ) ]</span>;
2981 use MooseX::Types::Moose
2984 subtype <span class="highlight">ArrayOfInt</span>,
2987 coerce <span class="highlight">ArrayOfInt</span>
2989 via { [ $_ ] };</code></pre>
2993 <h1>MooseX::Types</h1>
2995 <pre><code>package MyApp::Account;
2997 use MyApp::Types qw( ArrayOfInt );
2999 has transaction_history => (
3006 <h1>MooseX::Types</h1>
3009 <li>Type names are exported functions, catches typos early</li>
3010 <li>Types must be pre-declared</li>
3011 <li>Types are stored with namespaces internally, but externally are short</li>
3012 <li>Import existing Moose types as functions from <code>MooseX::Types::Moose</code></li>
3013 <li>Still need string names for things like <code>ArrayRef['Email::Address']</code></li>
3018 <h1>MooseX::Types Pros and Cons</h1>
3021 <li><span class="right">Catches typos at compile time</span></li>
3022 <li><span class="right">Automatic namespacing</span></li>
3023 <li><span class="wrong">One more thing to install and learn</span></li>
3024 <li><span class="wrong">Every name gets types twice (declared and then defined)</span></li>
3025 <li><span class="wrong">Still stuck with strings when referring to class or role names</span></li>
3026 <li><span class="wrong">Coercion gotcha from earlier still applies to types exported from <code>MooseX::Types::Moose</code></span></li>
3031 <h1>Recommendation</h1>
3034 <li>Use <code>MooseX::Types</code></li>
3035 <li>Compile time error catching and automatic namespacing are huge wins</li>
3036 <li>Docs from <code>Moose::Util::TypeConstraints</code> are 98% compatible with <code>MooseX::Types</code> anyway</li>
3037 <li>A function exported by a type library works wherever a type name would</li>
3049 # perl bin/prove -lv t/05-types.t
3051 Iterate til this passes all its tests</pre>
3054 <div class="slide fake-slide0">
3055 <h1>Part 6: Advanced Attributes</h1>
3059 <h1>Weak References</h1>
3062 <li>A weak reference lets you avoid circular references</li>
3063 <li>Weak references do not increase the reference count</li>
3068 <h1>Circular Reference Illustrated</h1>
3070 <pre><code>my $foo = {};
3071 my $bar = { foo => $foo };
3072 $foo->{bar} = $bar;</code></pre>
3075 <li>Neither <code>$foo</code> nor <code>$bar</code> go out of scope<br />
3076 (until the program exits)</li>
3081 <h1>Weakening Circular References</h1>
3083 <pre><code>use Scalar::Util qw( weaken );
3086 my $bar = { foo => $foo };
3087 $foo->{bar} = $bar;
3088 weaken $foo->{bar}</code></pre>
3091 <li>When <code>$bar</code> goes out of scope, <code>$foo->{bar}</code> becomes <code>undef</code></li>
3096 <h1>Circular References in Attributes</h1>
3098 <pre><code>package Person;
3101 has name => ( is => 'ro' );
3102 has friend => ( is => 'rw' );
3104 my $alice = Person->new( name => 'Alice' );
3105 my $bob = Person->new( name => 'Bob' );
3106 $bob->friend($alice);
3107 $alice->friend($bob);</code></pre>
3113 <pre><code>package Person;
3116 has name => ( is => 'ro' );
3117 has friend => ( is => 'rw',
3118 <span class="highlight">weak_ref => 1</span> );
3120 my $alice = Person->new( name => 'Alice' );
3121 my $bob = Person->new( name => 'Bob' );
3122 $bob->friend($alice);
3123 $alice->friend($bob);</code></pre>
3127 <h1>Under the Hood</h1>
3130 <li>A <code>weak_ref</code> attribute calls <code>weaken</code> ...
3132 <li>during object construction</li>
3133 <li>when the attribute is set via a writer</li>
3143 <li>A code reference run after an attribute is <em>set</em></li>
3144 <li>Like an <code>after</code> modifier, but makes intentions clearer</li>
3147 <h2 class="wrong">Gross</h2>
3149 <pre><code>after salary_level => {
3152 $self->clear_salary;
3157 <h1>Use a Trigger Instead</h1>
3159 <h2 class="right">Cleaner</h2>
3161 <pre><code>has salary_level => (
3163 trigger => sub { $_[0]->clear_salary },
3171 <li>Attributes can be objects</li>
3172 <li>Delegation transparently calls methods on those objects</li>
3177 <h1>Delegation Examples</h1>
3179 <pre><code>package Person;
3184 <span class="highlight">handles => [ 'inhale', 'exhale' ],</span>
3188 <li>Creates <code>$person->inhale</code> and <code>->exhale</code> methods</li>
3189 <li>Internally calls <code>$person->lungs->inhale</code></li>
3194 <h1>Why Delegation?</h1>
3197 <li>Reduce the number of classes exposed</li>
3198 <li>Re-arrange class internals -<br />
3199 turn a method into an attribute with delegation</li>
3200 <li>Provide convenenience methods</li>
3205 <h1>Moose's <code>handles</code> Parameter</h1>
3208 <li>Accepts many arguments ...
3210 <li>Array reference - list of methods to delegate as-is</li>
3211 <li>Hash reference - map of method names</li>
3212 <li>Regex - delegates all matching methods</li>
3213 <li>Role name - delegates all methods in the role</li>
3214 <li>Sub reference - does something complicated ;)</li>
3221 <h1>Array Reference</h1>
3224 <li>Takes each method name and creates a simple delegation from the delegating class to the delegatee attribute</li>
3229 <h1>Hash Reference</h1>
3232 <li>Mapping of names in the delegating class to the delegatee class</li>
3235 <pre><code>package Person;
3239 isa => 'BankAccount',
3240 <span class="highlight">handles => {
3241 receive_money => 'deposit',
3242 give_money => 'withdraw',
3248 <h1>Hash Reference Detailed</h1>
3250 <pre><code> handles => {
3251 receive_money => 'deposit',
3252 give_money => 'withdraw',
3256 <li><code>$person->receive_money</code> = <code>$person->account->deposit</code></li>
3257 <li><code>$person->give_money</code> = <code>$person->account->withdraw</code></li>
3264 <pre><code>package Person;
3270 handles => qr/.*/,
3274 <li>Creates a delegation for every method in the Name class</li>
3275 <li>Excludes <code>meta</code> and methods inherited from <code>Moose::Object</code></li>
3282 <pre><code>package Auditor;
3284 sub record_change { ... }
3285 sub change_history { ... }
3292 does => 'Auditor',
3293 <span class="highlight">handles => 'Auditor',</span>
3298 <h1>Role Name Detailed</h1>
3301 <li>Account gets delegate methods for each method in the <code>Auditor</code> role
3303 <li>record_history</li>
3304 <li>change_history</li>
3311 <h1>Native Delegation</h1>
3314 <li>Delegate to <em>unblessed</em> Perl types</li>
3315 <li>Scalar, array or hash ref, etc</li>
3320 <h1>Native Delegation - Array</h1>
3322 <pre><code>package Person;
3324 has _favorite_numbers => (
3325 traits => [ 'Array' ],
3327 isa => 'ArrayRef[Int]',
3328 default => sub { [] },
3329 init_arg => undef,
3330 <span class="highlight">handles =>
3331 { favorite_numbers => 'elements',
3332 add_favorite_number => 'push',
3338 <h1>Native Delegation - Counter</h1>
3340 <pre><code>package Stack;
3343 traits => [ 'Counter' ],
3347 init_arg => undef,
3348 <span class="highlight">handles =>
3349 { _inc_depth => 'inc',
3350 _dec_depth => 'dec',
3357 <h1>Traits and Metaclasses</h1>
3360 <li>The ultimate in customization</li>
3361 <li>Per attribute metaclasses</li>
3362 <li>Per attribute roles applied to the attribute metaclass</li>
3363 <li>Change the meta-level behavior</li>
3368 <h1>Traits and Metaclasses</h1>
3371 <li>The default metaclass is <code>Moose::Meta::Attribute</code></li>
3372 <li>Controls accessor generation, defaults, delegation, etc.</li>
3373 <li>Adding a role to this metaclass (or replacing it) allows for infinite customization</li>
3378 <h1>Traits and Metaclasses</h1>
3381 <li>Can add/alter/remove attribute parameter (from <code>has</code>)</li>
3382 <li>Can change behavior of created attribute</li>
3387 <h1>Simple Trait Example</h1>
3389 <pre><code>package Person;
3391 use MooseX::LabeledAttributes;
3394 <span class="highlight">traits => [ 'Labeled' ],</span>
3397 <span class="highlight">label => 'Social Security Number',</span>
3399 print <span class="highlight">Person->meta
3400 ->get_attribute('ssn')->label;</span></code></pre>
3404 <h1>Simple Metaclass Example</h1>
3406 <pre><code>package Person;
3408 use MooseX::LabeledAttributes;
3411 <span class="highlight">metaclass =>
3412 'MooseX::Meta::Attribute::Labeled',</span>
3415 <span class="highlight">label => 'Social Security Number',</span>
3417 print <span class="highlight">Person->meta
3418 ->get_attribute('ssn')->label;</span></code></pre>
3422 <h1>Traits vs Metaclass</h1>
3425 <li>Can apply any mix of traits to an attribute</li>
3426 <li>But just one metaclass</li>
3427 <li>Traits (aka roles) can cooperate</li>
3428 <li>Metaclasses require you to pick just one</li>
3433 <h1>Advanced Attributes Summary</h1>
3436 <li>Use <code>weak_ref</code> to avoid circular references</li>
3437 <li>Use trigger to do an action post-attribute write</li>
3438 <li>Use delegations to hide "internal" objects</li>
3439 <li>Traits and metaclasses let you extend Moose's core attribute features</li>
3451 # perl bin/prove -lv \
3452 t/06-advanced-attributes.t
3454 Iterate til this passes all its tests</pre>
3457 <div class="slide fake-slide0">
3458 <h1>Part 7: Introspection</h1>
3461 <div class="slide fake-slide0">
3462 <h1>Part 8: A Tour of MooseX</h1>
3465 <div class="slide fake-slide0">
3466 <h1>Part 9: Writing Moose Extensions</h1>
3469 <div class="slide fake-slide0">
3474 <h1>More Information</h1>
3477 <li><a href="http://moose.perl.org/">http://moose.perl.org/</a></li>
3478 <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>
3479 <li><a href="irc://irc.perl.org/#moose">irc://irc.perl.org/#moose</a></li>
3480 <li>mailing list - <a href="mailto:moose@perl.org">moose@perl.org</a></li>
3481 <li>Slides and exercises are in Moose's git repo:
3483 <span style="white-space: nowrap">git://jules.scsys.co.uk/gitmo/moose-presentations</span></li>
3493 Copyright 2009 David Rolsky. All Rights Reserved.
3495 This work is licensed under a Creative Commons Attribution-Share Alike
3496 3.0 United States License See
3497 http://creativecommons.org/licenses/by-sa/3.0/us/ for details.