- Calls
Person->BUILDARGS(@_)
to turn @_
into a hashref
- Blesses a reference
- Populates attributes based on the hashref from #1
@@ -940,7 +962,7 @@ sub BUILD {
-
The Object is Oqaque
+
The Object is Opaque
- Technically it's a hash reference
@@ -962,6 +984,8 @@ sub BUILD {
extends
is sugar for declaring parent classes
+ - Also ensures metaclass compatibility between parent and child
+ - Do not
use base
package Employee;
@@ -1029,7 +1053,8 @@ use Moose;
override work => sub {
my $self = shift;
- die "Pay me first" unless $self->got_paid;
+ die "Pay me first"
+ unless $self->got_paid;
super();
};
@@ -1127,6 +1152,7 @@ Person->can('extends');
no Moose
at the end of a package is a best practice
+ - Or
use namespace::autoclean
at the top
- Just do it
@@ -1187,12 +1213,15 @@ use Moose;
Exercises
# cd exercises
-$ perl bin/prove -lv t/00-prereq.t
-Missing anything? Install it. (see tarballs/)
+# perl bin/prove -lv t/00-prereq.t
+
+# perl install-moose (if needed)
# perl bin/prove -lv t/01-classes.t
+# edit lib/Person.pm and lib/Employee.pm
+
Iterate til this passes all its tests
@@ -1210,11 +1239,10 @@ Iterate til this passes all its tests
-
Roles Can Have State and Behavior
+
Roles - State and Behavior
package HasPermissions;
use Moose::Role;
-
# state
has access_level => ( is => 'rw' );
@@ -1223,7 +1251,8 @@ sub can_access {
my $self = shift;
my $required = shift;
- return $self->access_level >= $required;
+ return $self->access_level
+ >= $required;
}
@@ -1267,8 +1296,8 @@ with 'HasPermissions';
Classes Consume Roles
my $person = Person->new(
- first_name => 'Kenichi',
- last_name => 'Asai',
+ first_name => 'Kenichi',
+ last_name => 'Asai',
access_level => 42,
);
@@ -1324,7 +1353,7 @@ sub print {
# or ...
-if ( Person->meta->does('Printable') ) { ... }
+Person->meta->does('Printable')
@@ -1390,10 +1419,10 @@ use Moose;
use Moose;
with 'IsFragile' =>
- { alias =>
+ { -alias =>
{ break => 'break_bone' } },
'CanBreakdance' =>
- { alias =>
+ { -alias =>
{ break => 'break_it_down' } };
@@ -1409,13 +1438,13 @@ use Moose;
use Moose;
with 'IsFragile' =>
- { alias =>
+ { -alias =>
{ break => 'break_bone' },
- exclude => 'break' },
+ -excludes => 'break' },
'CanBreakdance' =>
- { alias =>
- { break => 'break_dance' },
- exclude => 'break' };
+ { -alias =>
+ { break => 'break_it_down' },
+ -excludes => 'break' };
@@ -1427,7 +1456,7 @@ use Moose;
sub break {
my $self = shift;
- $self->break_dance;
+ $self->break_it_down;
if ( rand(1) < 0.5 ) {
$self->break_bone;
}
@@ -1588,7 +1617,8 @@ has [ 'left', 'right' ] => (
use Moose::Util qw( apply_all_roles );
my $fragile_person = Person->new( ... );
-apply_all_roles( $fragile_person, 'IsFragile' );
+apply_all_roles( $fragile_person,
+ 'IsFragile' );
- Does not change the
Person
class
@@ -1751,7 +1781,7 @@ Person->new(); # kaboom
- Attributes can have defaults
- - Simple non-referecne scalars (number, string)
+ - Simple non-reference scalars (number, string)
- Subroutine reference
- A builder method
@@ -1792,7 +1822,7 @@ has bank => (
-
Default as a Subroutine Reference
+
Subroutine Reference Default
- Called as a method on the object
@@ -1865,7 +1895,8 @@ has bank => (
sub _build_bank {
my $self = shift;
- return Bank->new( name => 'Spire FCU' );
+ return Bank->new(
+ name => 'Spire FCU' );
}
@@ -1904,7 +1935,7 @@ has bank => (
-
Lazy, Good for Nothing Attributes
+
Lazy, Good for Nothin' Attributes
- Normally, defaults are generated during object construction
@@ -2188,7 +2219,8 @@ has first_name => (
Exercises
# cd exercises
-# perl bin/prove -lv t/03-basic-attributes.t
+# perl bin/prove -lv \
+ t/03-basic-attributes.t
Iterate til this passes all its tests
@@ -2257,7 +2289,8 @@ before work => sub {
my $self = shift;
return unless $DEBUG;
- warn "Called work on ", $self->full_name,
+ warn "Called work on ",
+ $self->full_name,
"with the arguments: [@_]\n";
};
@@ -2289,19 +2322,17 @@ after work => sub {
-
Other Uses Example
+
More Modifier Examples
has password => (
is => 'rw',
clearer => 'clear_password',
);
-
has hashed_password => (
is => 'ro',
builder => '_build_hashed_password',
clearer => '_clear_hashed_password',
);
-
after clear_password => sub {
my $self = shift;
$self->_clear_hashed_password;
@@ -2342,7 +2373,6 @@ after clear_password => sub {
$self->_munge_insert(@_) );
$new_user->_assign_uri;
-
return $new_user;
};
@@ -2351,7 +2381,7 @@ after clear_password => sub {
Modifier Order
- - Before runs order from last to first
+ - Before runs in order from last to first
- After runs in order from first to last
- Around runs in order from last to first
@@ -2420,13 +2450,11 @@ sub xml { '<doc>' . inner() . '</doc>
package Report;
extends 'Document';
-
augment xml =>
sub { title() . inner() . summary() };
package TPSReport;
extends 'Report';
-
augment xml =>
sub { tps_xml() . inner() };
@@ -2507,7 +2535,8 @@ extends 'Report';
Exercises
# cd exercises
-# perl bin/prove -lv t/04-method-modifiers.t
+# perl bin/prove -lv \
+ t/04-method-modifiers.t
Iterate til this passes all its tests
@@ -2516,6 +2545,538 @@ Iterate til this passes all its tests
Part 5: Types
+
+
A Type System for Perl
+
+
+ - Sort of ...
+ - Variables are not typed
+ - Attributes can have types
+ - MooseX modules let you define method signatures
+
+
+
+
+
Components of a Moose Type
+
+
+ - A type is a name and a constraint
+ - Types have a hierarchy
+ - Constraints are cumulative from parents
+ - Types can have associated coercions
+
+
+
+
+
Built-in Type Hierarchy
+
+
+Any
+Item
+ Bool
+ Maybe[`a]
+ Undef
+ Defined
+ Value
+ Str
+ Num
+ Int
+ ClassName
+ RoleName
+
+
+
+
+
Built-in Type Hierarchy
+
+
+(Item)
+ (Defined)
+ (Value)
+ Ref
+ ScalarRef
+ ArrayRef[`a]
+ HashRef[`a]
+ CodeRef
+ RegexpRef
+ GlobRef
+ FileHandle
+ Object
+
+
+
+
+
Bool
+
+
True
+
1
+924.1
+'true'
+{}
+
+
False
+
0
+0.0
+'0'
+undef
+
+
+ - Like Perl's
if ($foo)
+
+
+
+
+
Value (and subtypes)
+
+
+ Value
is true when ! ref $thing
+ Value
and Str
are effectively the same, but Str
is more expressive
+ Num
is true when a $scalar
looks like a number
+ - An overloaded object which numifies does not pass the
Num
constraint!
+ - Perl 5's overloading is hopelessly broken
+
+
+
+
+
ClassName and RoleName
+
+
+ - A string with a package name
+ - The package must already be loaded
+
+
+
+
+
Parameterizable Types
+
+
+ - What does
ArrayRef[`a]
mean?
+ s/`a/Int/
(or Str
or ...)
+ - When you use it you can write ...
+
+ ArrayRef
(== ArrayRef[Item]
)
+ ArrayRef[Str]
+ ArrayRef[MyTypeName]
+ ArrayRef[HashRef[Maybe[Int]]]
+
+
+
+
+
+
+
Maybe[`a]
+
+
+ - Maybe means either the named type or
undef
+ Maybe[Int]
accepts integers or undef
+
+
+
+
+
Type Union
+
+
+ - This or that (or that or ...)
+ Int | ArrayRef[Int]
+ - But use a coercion instead when possible
+ - Or use a
role_type
, duck_type
, or anything not a union
+ - A union is often a code smell
+
+
+
+
+
Making Your Own Types
+
+
use Moose::Util::TypeConstraints;
+
+subtype 'PositiveInt',
+ as 'Int',
+ where { $_ > 0 },
+ message
+ { "The value you provided ($_)"
+ . " was not a positive int." };
+
+has size => (
+ is => 'ro',
+ isa => 'PositiveInt',
+);
+
+
+
+
Automatic Types
+
+
+ - Moose creates a type for every Moose class and role
+ - Unknown names are assumed to be classes
+
+
+
+
+
Automatic Types
+
+
package Employee;
+use Moose;
+
+has manager => (
+ is => 'rw',
+ isa => 'Employee',
+);
+
+has start_date => (
+ is => 'ro',
+ isa => 'DateTime',
+);
+
+
+
+
Subtype Shortcuts - class_type
+
+
use Moose::Util::TypeConstraints;
+class_type 'DateTime';
+
+subtype 'DateTime',
+ as 'Object',
+ where { $_->isa('DateTime') },
+ message { ... };
+
+
+
+
Subtype Shortcuts - role_type
+
+
use Moose::Util::TypeConstraints;
+role_type 'Printable';
+
+subtype 'Printable',
+ as 'Object',
+ where
+ { Moose::Util::does_role(
+ $_, 'Printable' ) },
+ message { ... };
+
+
+
+
Subtype Shortcuts - duck_type
+
+
use Moose::Util::TypeConstraints;
+duck_type Car => qw( run break_down );
+
+subtype 'Car',
+ as 'Object',
+ where { all { $_->can($_) }
+ qw( run break_down ) },
+ message { ... };
+
+
+
+
Subtype Shortcuts - enum
+
+
use Moose::Util::TypeConstraints;
+enum Color => qw( red blue green ) );
+
+my %ok = map { $_ => 1 }
+ qw( red blue green );
+
+subtype 'Color'
+ as 'Str',
+ where { $ok{$_} },
+ message { ... };
+
+
+
+
Anonymous Subtypes
+
+
package Person;
+
+my $posint =
+ subtype as 'Int', where { $_ > 0 };
+
+has size => (
+ is => 'ro',
+ isa => $posint,
+);
+
+
+ - Shortcuts have anonymous forms as well
+
+
+
+
+
Coercions
+
+
use Moose::Util::TypeConstraints;
+
+subtype 'UCStr',
+ as 'Str',
+ where { ! /[a-z]/ };
+
+
+
+
Coercions
+
+
coerce 'UCStr',
+ from 'Str',
+ via { uc };
+
+has shouty_name => (
+ is => 'ro',
+ isa => 'UCStr',
+ coerce => 1,
+);
+
+
+
+
Coercion Examples
+
+
subtype 'My::DateTime',
+ as class_type 'DateTime';
+
+coerce 'My::DateTime',
+ from 'HashRef',
+ via { DateTime->new( %{$_} ) };
+
+coerce 'My::DateTime',
+ from 'Int',
+ via { DateTime->from_epoch(
+ epoch => $_ ) };
+
+
+ - Use coercion to inflate a value
+
+
+
+
+
Coercion Examples
+
+
coerce 'ArrayRef[Int]',
+ from 'Int',
+ via { [ $_ ] };
+
+
+ - Instead of union -
Int | ArrayRef[Int]
+
+
+
+
+
Using Types with Attributes
+
+
package Person;
+
+has height => (
+ is => 'rw',
+ isa => 'Num',
+);
+
+has favorite_numbers => (
+ is => 'rw',
+ isa => 'ArrayRef[Int]',
+ coerce => 1,
+);
+
+
+
+
More Droppings
+
+
+ Moose::Util::TypeConstraints
also needs cleanup
+
+
+
package Person;
+
+use Moose;
+use Moose::Util::TypeConstraints;
+
+subtype ...;
+
+no Moose;
+no Moose::Util::TypeConstraints;
+
+
+
+
Typed Methods (Low-tech)
+
+
package Person;
+use MooseX::Params::Validate qw( validated_list );
+
+sub work {
+ my $self = shift;
+ my ( $tasks, $can_rest ) =
+ validated_list(
+ \@_,
+ tasks =>
+ { isa => 'ArrayRef[Task]',
+ coerce => 1 },
+ can_rest =>
+ { isa => 'Bool',
+ default => 0 },
+ );
+ ...
+}
+
+
+
+
Typed Methods (High-tech)
+
+
package Person;
+
+use MooseX::Method::Signatures;
+
+method work ( ArrayRef[Task] :$tasks,
+ Bool :$can_rest = 0 ) {
+ my $self = shift;
+
+ ...
+}
+
+
+
+
Digression: The Type Registry
+
+
+ - Types are actually
Moose::Meta::TypeConstraints
objects
+ - Stored in an interpreter-global registry mapping names to objects
+
+
+
+
+
Danger!
+
+
+ - Coercions are attached to type objects
+ - Therefore also global
+ - Name conflicts between modules!
+ - Coercion conflicts between modules!
+
+
+
+
+
Namespace Fix
+
+
+ - Use some sort of pseudo-namespacing scheme
+ - Never coerce directly to a class name, or to built-in types
+
+
+
+
+
Namespace Fix
+
+
use Moose::Util::TypeConstraints;
+subtype 'MyApp::Type::DateTime',
+ as 'DateTime';
+
+coerce 'MyApp::Type::DateTime',
+ from 'HashRef',
+ via { DateTime->new( %{$_} ) }
+
+has creation_date => (
+ is => 'ro',
+ isa => 'MyApp::Type::DateTime',
+ coerce => 1,
+);
+
+
+
+
Namespace Fix
+
+
subtype 'MyApp::Type::ArrayOfInt',
+ as 'ArrayRef[Int]';
+
+coerce 'MyApp::Type::ArrayOfInt',
+ from 'Int',
+ via { [ $_ ] };
+
+
+
+
Namespace Fix Pros and Cons
+
+
+ - Relatively simple
+ - Already built into Moose
+ - Conflates type and module namespaces
+ - Type names are strings, so typos are easy to make and may be hard to find
+
+
+
+
+
MooseX::Types
+
+
package MyApp::Types;
+
+use MooseX::Types
+ -declare => [ qw( ArrayOfInt ) ];
+use MooseX::Types::Moose
+ qw( ArrayRef Int );
+
+subtype ArrayOfInt,
+ as ArrayRef[Int];
+
+coerce ArrayOfInt
+ from Int,
+ via { [ $_ ] };
+
+
+
+
MooseX::Types
+
+
package MyApp::Account;
+
+use MyApp::Types qw( ArrayOfInt );
+
+has transaction_history => (
+ is => 'rw',
+ isa => ArrayOfInt,
+);
+
+
+
+
MooseX::Types
+
+
+ - Type names are exported functions, catches typos early
+ - Types must be pre-declared
+ - Types are stored with namespaces internally, but externally are short
+ - Import existing Moose types as functions from
MooseX::Types::Moose
+ - Still need string names for things like
ArrayRef['Email::Address']
+
+
+
+
+
MooseX::Types Pros and Cons
+
+
+ - Catches typos at compile time
+ - Automatic namespacing
+ - One more thing to install and learn
+ - Every name gets types twice (declared and then defined)
+ - Still stuck with strings when referring to class or role names
+ - Coercion gotcha from earlier still applies to types exported from
MooseX::Types::Moose
+
+
+
+
+
Recommendation
+
+
+ - Use
MooseX::Types
+ - Compile time error catching and automatic namespacing are huge wins
+ - Docs from
Moose::Util::TypeConstraints
are 98% compatible with MooseX::Types
anyway
+ - A function exported by a type library works wherever a type name would
+
+
+
+
+
Questions?
+
+
+
+
Exercises
+
+
# cd exercises
+# perl bin/prove -lv t/05-types.t
+
+Iterate til this passes all its tests
+
+
Part 6: Advanced Attributes
@@ -2579,7 +3140,8 @@ $alice->friend($bob);
use Moose;
has name => ( is => 'ro' );
-has friend => ( is => 'rw', weak_ref => 1 );
+has friend => ( is => 'rw',
+ weak_ref => 1 );
my $alice = Person->new( name => 'Alice' );
my $bob = Person->new( name => 'Bob' );
@@ -2698,7 +3260,6 @@ has lungs => (
package Person;
use Moose;
-
has account => (
is => 'ro',
isa => 'BankAccount',
@@ -2746,7 +3307,6 @@ has name => (
package Auditor;
use Moose::Role;
-
sub record_change { ... }
sub change_history { ... }
@@ -2774,6 +3334,120 @@ has history => (
+
Native Delegation
+
+
+ - Delegate to unblessed Perl types
+ - Scalar, array or hash ref, etc
+ - Treat Perl types as objects
+ - Still uses
handles
+ - Pretend that native Perl types have methods
+
+
+
+
+
Native Delegation - Array(Ref)
+
+
+ - Methods include:
+
+ push
+ shift
+ elements
- returns all elements
+ count
+ is_empty
+ - quite a few more
+
+
+
+
+
+
+
Native Delegation - Array(Ref)
+
+
package Person;
+use Moose;
+has _favorite_numbers => (
+ traits => [ 'Array' ],
+ is => 'ro',
+ isa => 'ArrayRef[Int]',
+ default => sub { [] },
+ init_arg => undef,
+ handles =>
+ { favorite_numbers => 'elements',
+ add_favorite_number => 'push',
+ },
+);
+
+
+
+
Native Delegation - Array(Ref)
+
+
my $person = Person->new();
+
+$person->add_favorite_number(7);
+$person->add_favorite_number(42);
+
+print "$_\n"
+ for $person->favorite_numbers;
+
+# 7
+# 42
+
+
+
+
Native Delegation
+
+
+ - Native types are ...
+
+ - Number -
add
, mul
, ...
+ - String -
append
, chop
, ...
+ - Counter -
inc
, dec
, ...
+ - Bool -
set
, toggle
, ...
+ - Hash -
get
, set
, ...
+ - Array - already saw it
+ - Code -
execute
, that's it
+
+
+
+
+
+
+
Curried Delegation
+
+
+ - A delegation with some preset arguments
+ - Works with object or Native delegation
+
+
+
+
+
Curried Delegation
+
+
package Person;
+use Moose;
+has account => (
+ is => 'ro',
+ isa => 'BankAccount',
+ handles => {
+ receive_100 =>
+ [ 'deposit', 100 ]
+ give_100 =>
+ [ 'withdraw', 100 ]
+ },
+);
+
+
+
+
Curried Delegation
+
+
$person->receive_100;
+# really is
+$person->account->deposit(100);
+
+
+
Traits and Metaclasses
@@ -2816,7 +3490,6 @@ has ssn => (
isa => 'Str',
label => 'Social Security Number',
);
-
print Person->meta
->get_attribute('ssn')->label;
@@ -2835,7 +3508,6 @@ has ssn => (
isa => 'Str',
label => 'Social Security Number',
);
-
print Person->meta
->get_attribute('ssn')->label;
@@ -2870,7 +3542,8 @@ print Person->meta
Exercises
# cd exercises
-# perl bin/prove -lv t/06-advanced-attributes.t
+# perl bin/prove -lv \
+ t/06-advanced-attributes.t
Iterate til this passes all its tests
@@ -2880,9 +3553,200 @@ Iterate til this passes all its tests
-
Part 8: A Tour of MooseX
+ Part 8: A Brief Tour of MooseX
+
+
+
+
Notable MX Modules on CPAN
+
+
+ - Not comprehensive
+ - 128 MooseX distributions on CPAN as of 09/24/2009
+ - Some of them are crap
+
+
+
+
+
Already Mentioned Several
+
+
+ MooseX::NonMoose
- best solution for subclassing non-Moose parents
+ MooseX::Declare
- real Perl 5 OO
+ MooseX::FollowPBP
and MooseX::SemiAffordanceAccessor
+ MooseX::Params::Validate
and MooseX::Method::Signatures
+ MooseX::Types
+
+
+
+
+
MooseX::Declare
+
+
use MooseX::Declare;
+use 5.10.0; # for say
+
+class Person {
+ has greeting =>
+ ( is => 'ro', isa => 'Str' );
+
+ method speak {
+ say $self->greeting;
+ }
+}
+
+
+
+
MooseX::Declare
+
+
+ - Still experimental-ish, but seeing more and more use
+ - Not a source filter!
+ - Hooks into the Perl parser rather than filtering all your code
+ - But not supported by
PPI
, perltidy
, etc. (yet?)
+
+
+
MooseX::StrictConstructor
+
+
+ - By default, unknown constructor arguments are ignored
+ - MX::StrictConstructor turns these into an error
+
+
+
+
+
MooseX::StrictConstructor
+
+
package Person;
+
+use Moose;
+use MooseX::StrictConstructor;
+
+has name => ( is => 'ro' );
+
+Person->new
+ ( nane => 'Ringo Shiina' ); # kaboom
+
+
+
+
MooseX::Traits
+
+
+ - Combines object construction and role application
+ - Makes it easy to create one-off customized objects
+
+
+
+
+
MooseX::Traits
+
+
package MyApp::Thingy;
+use Moose;
+
+with 'MooseX::Traits';
+
+my $thing =
+ MyApp::Thingy->new_with_traits
+ ( traits => [ 'Foo', 'Bar' ],
+ size => 42 );
+
+
+
+
MooseX::Getopt
+
+
+ - Makes command-line interface programs easy!
+ - Construct an object from CLI arguments
+
+
+
+
+
MooseX::Getopt
+
+
package App::CLI;
+use Moose;
+
+with 'MooseX::Getopt';
+
+has file =>
+ ( is => 'ro', required => 1 );
+has filters =>
+ ( is => 'ro', isa => 'Str' );
+
+sub run { ... }
+
+
+
+
MooseX::Getopt
+
+
+ - Then call it like this:
+
+
+
#!/usr/bin/perl
+
+use App::CLI;
+
+App::CLI->new_with_options()->run();
+
+
$ myapp-cli \
+ --file foo \
+ --filters compress \
+ --filters sanitize
+
+
+
+
MooseX::Clone
+
+
package Person;
+
+use Moose;
+with 'MooseX::Clone';
+
+my $person = Person->new;
+my $clone = $person->clone;
+
+
+
+
MooseX::NonMoose
+
+
+ - Highly recommended for subclassing non-Moose parents
+ - Gets all the little annoying details right
+
+
+
+
+
MooseX::Role::Parameterized
+
+
package HasCollection;
+use MooseX::Role::Parameterized;
+parameter type => ( isa => 'Str',
+ default => 'Item' );
+role {
+ my $p = shift;
+
+ my $type =
+ 'ArrayRef[' . $p->type() . ']';
+ has collection =>
+ ( is => 'ro',
+ isa => $type );
+};
+
+
+
+
MooseX::Role::Parameterized
+
+
package Person;
+
+use Moose;
+with HasCollection => { type => 'Int' };
+
+
+
+
Questions?
+
+
Part 9: Writing Moose Extensions