SlideShare ist ein Scribd-Unternehmen logo
1 von 35
Moose




Sawyer X
Sawyer X
blogs.perl.org/users/sawyer_x
search.cpan.org/~xsawyerx
metacpan.org/author/XSAWYERX
github.com/xsawyerx/
„The Dancer guy!“
Projects: Dancer, Module::Starter, MetaCPAN::API,
 MooseX::Role::Loggable, etc.
Moose
Object system
Metaclass-based
Advanced
Sophisticated
Extensible
Production-ready
… but why Moose?
package Person;                                            package User;

use strict;                                                use Email::Valid;
use warnings;                                              use Moose;
                                                           use Moose::Util::TypeConstraints;
use Carp qw( confess );
use DateTime;                                              extends 'Person';
use DateTime::Format::Natural;
                                                           subtype 'Email'
                                                               => as 'Str'
sub new {                                                      => where { Email::Valid­>address($_) }
    my $class = shift;                                         => message { "$_ is not a valid email 
    my %p = ref $_[0] ? %{ $_[0] } : @_;                   address" };

    exists $p{name}                                        has email_address => (
        or confess 'name is a required attribute';             is       => 'rw',
    $class­>_validate_name( $p{name} );                        isa      => 'Email',
                                                               required => 1,
    exists $p{birth_date}                                  );
        or confess 'birth_date is a required attribute';

    $p{birth_date} = $class­
>_coerce_birth_date( $p{birth_date} );
    $class­>_validate_birth_date( $p{birth_date} );

    $p{shirt_size} = 'l'
        unless exists $p{shirt_size}:

    $class­>_validate_shirt_size( $p{shirt_size} );

    return bless %p, $class;
}

sub _validate_name {
    shift;
    my $name = shift;

    local $Carp::CarpLevel = $Carp::CarpLevel + 1;

    defined $name
        or confess 'name must be a string';
}
Get it?
Writing objects in basic Perl 5
Create a reference (usually to a hash)
Connect it to a package (using „bless“)
Provide subroutines that access the hash keys
Error check the hell out of it
Writing objects in basic Perl 5, e.g.
package Dog;
use strict; use warnings;
sub new {
     my $class = shift;
     my $self   = bless {}, $class;
     return $self;
}
1;
Issues
Defining the same new() concept every time
No parameters for new() yet
Will have to do all error-checking manually
Moose
package Dog;


use Moose;


1;
You get
use strict;
use warnings;
new() method
To hell with ponies, you get a moose!
(roll picture of a moose beating a pony in soccer)
Full affordance accessors (attributes)
has name => ( is => 'rw' );
„ro“ is available for read-only attributes
You can manually change setter/getter via writer/reader
Attributes can have defaults
Attributes can have type constraints
Attributes can have traits
Attributes can be lazy, have builders, clearers, predicates...
Type constraints
has name => ( is => 'ro', isa => 'Str' );
Str, Int, Bool, ArrayRef, HashRef, CodeRef, Regex,
 Classes
Combine: ArrayRef|HashRef, ArrayRef[Str]
Derivatives (Int is a Num)
Create your own using subtype, available at
 Moose::Util::TypeConstraints
Methods
Same as before
sub run {
      my $self = shift;
       say qq{I make it a habit only to run when
    being chased!};
}
Inheritance easy as...
package Punk
use Moose;
extends 'Person';
Multiple inheritance also possible (extends accepts array)
package Child;
use Moose;
extends qw/Father Mother/;
Roles are even better
package Punk;
use Moose;
with qw/Tattoos Piercings Squatter/;


Roles are things you do, instead of things you are.
More hooks than a coat rack!
package User::WinterAware;
use Moose;
extends 'User';
before leaving => sub {
  my $self = shift;
  $self->cold and $self->take_jacket;
};
More hooks than a coat rack!
package User::Secure;
use Moose;
extends 'User';
around login => sub {
  my $orig = shift;
  my $self = shift;
  $self->security_check and $self->$orig(@_);
};
More hooks than a coat rack!
Before
After
Around
Inner
Augment
Back to attributes...
has set => (
  is         => 'rw',
  isa        => 'Set::Object',
  default    => sub { Set::Object->new },
  required   => 1,
  lazy       => 1,
  predicate => 'has_set',
  clearer    => 'clear_set',
Attribute options: default
default => 'kitteh'                  # string
default => 3                         # number
default => sub { {} }                # HashRef
default => sub { [] }                # ArrayRef
default => sub { Object->new } # an Object


    (if you need a more elaborate sub, use builder)
Attribute options: required
required => 1 # required
required => 0 # not required
Attribute options: lazy
lazy => 1 # make it lazy


Class will not create the slot for this attribute unless it
absolutely has to, defined by whether it is accessed at all.


No access? No penalty!
Lazy == good
Attribute options: builder
builder => 'build_it' # subroutine name


sub build_it {
    my $self = shift; # not a problem!
  return Some::Object->new( $self-
>more_opts );
}
Attribute options: clearer
clearer => 'clear_it' # subroutine name


# you don't need to create the subroutine
sub time_machine {
    my $self = shift;
    $self->clear_it; # 'it' never happened :)
}
Attribute options: predicate
predicate => 'has_it' # subroutine name


# you don't need to create the subroutine
sub try_to_do_it {
    my $self = shift;
    $self->has_it && $self->do_it();
}
Attribute options: lazy_build
lazy_build => 1 # <3


# the same as:
lazy        => 1,
builder     => '_build_it', # private
clearer     => 'clear_it',
predicate => 'has_it',
Example: Comican
A hub for various comics strips
Allow you to fetch comic strips
Standard uniformed interface to add more comics
We'll be using:
  Roles
  Lazy attributes
  Overriding attributes options
  Attribute predicates
Comican
      comic modules        Comican::Comic::Dilber
                                     t              interface
                                                      role
       Comican::Comic::PennyArcade

Comican::Comic::xkcd                                 Comican::
                                                    Role::Comic

                          main module
   user


                             Comican.pm
Comican: overall
Comican.pm is the user's interface
It's a hub for Comican::Comic::* modules
They are objects that fetch specific comic strips
They have a common interface
Defined by Comican::Role::Comic
SHOW ME THE CODE!
/^M(?:o(?:o|[ou]se)?)?$/
Moose: standart
Mouse: subset, uses XS, faster
(Any::Moose: use Mouse unless Moose already loaded)
Moo: Pure-Perl, subset, blazing fast
Mo: As little as possible (incl. character count)
M: Really as little as possible
Hummus (HuMoose): Incompatible chickpeas paste
Thank you.

Weitere ähnliche Inhalte

Was ist angesagt?

CoffeeScript
CoffeeScriptCoffeeScript
CoffeeScript
None
 
Writing Friendly libraries for CodeIgniter
Writing Friendly libraries for CodeIgniterWriting Friendly libraries for CodeIgniter
Writing Friendly libraries for CodeIgniter
CodeIgniter Conference
 
Good Evils In Perl
Good Evils In PerlGood Evils In Perl
Good Evils In Perl
Kang-min Liu
 

Was ist angesagt? (20)

Introduction To Moose
Introduction To MooseIntroduction To Moose
Introduction To Moose
 
CoffeeScript
CoffeeScriptCoffeeScript
CoffeeScript
 
Introduction to CoffeeScript
Introduction to CoffeeScriptIntroduction to CoffeeScript
Introduction to CoffeeScript
 
Coffee Script
Coffee ScriptCoffee Script
Coffee Script
 
DBIx::Class beginners
DBIx::Class beginnersDBIx::Class beginners
DBIx::Class beginners
 
DBIx::Class introduction - 2010
DBIx::Class introduction - 2010DBIx::Class introduction - 2010
DBIx::Class introduction - 2010
 
Writing Friendly libraries for CodeIgniter
Writing Friendly libraries for CodeIgniterWriting Friendly libraries for CodeIgniter
Writing Friendly libraries for CodeIgniter
 
Doctrine MongoDB ODM (PDXPHP)
Doctrine MongoDB ODM (PDXPHP)Doctrine MongoDB ODM (PDXPHP)
Doctrine MongoDB ODM (PDXPHP)
 
Puppet Camp Paris 2015: Power of Puppet 4 (Beginner)
Puppet Camp Paris 2015: Power of Puppet 4 (Beginner) Puppet Camp Paris 2015: Power of Puppet 4 (Beginner)
Puppet Camp Paris 2015: Power of Puppet 4 (Beginner)
 
Power of Puppet 4
Power of Puppet 4Power of Puppet 4
Power of Puppet 4
 
Good Evils In Perl
Good Evils In PerlGood Evils In Perl
Good Evils In Perl
 
LPW: Beginners Perl
LPW: Beginners PerlLPW: Beginners Perl
LPW: Beginners Perl
 
WordPress Cuztom Helper
WordPress Cuztom HelperWordPress Cuztom Helper
WordPress Cuztom Helper
 
"The worst code I ever wrote"
"The worst code I ever wrote""The worst code I ever wrote"
"The worst code I ever wrote"
 
Constructive Destructor Use
Constructive Destructor UseConstructive Destructor Use
Constructive Destructor Use
 
Perl
PerlPerl
Perl
 
Going crazy with Node.JS and CakePHP
Going crazy with Node.JS and CakePHPGoing crazy with Node.JS and CakePHP
Going crazy with Node.JS and CakePHP
 
Advanced Perl Techniques
Advanced Perl TechniquesAdvanced Perl Techniques
Advanced Perl Techniques
 
Introduction to Perl Best Practices
Introduction to Perl Best PracticesIntroduction to Perl Best Practices
Introduction to Perl Best Practices
 
Your JavaScript Library
Your JavaScript LibraryYour JavaScript Library
Your JavaScript Library
 

Andere mochten auch

Java. Lecture 03. OOP and UML
Java. Lecture 03. OOP and UMLJava. Lecture 03. OOP and UML
Java. Lecture 03. OOP and UML
colriot
 
Perl.Hacks.On.Vim
Perl.Hacks.On.VimPerl.Hacks.On.Vim
Perl.Hacks.On.Vim
Lin Yo-An
 

Andere mochten auch (12)

Java. Lecture 03. OOP and UML
Java. Lecture 03. OOP and UMLJava. Lecture 03. OOP and UML
Java. Lecture 03. OOP and UML
 
A very nice presentation on Moose.
A very nice presentation on Moose.A very nice presentation on Moose.
A very nice presentation on Moose.
 
Moose workshop
Moose workshopMoose workshop
Moose workshop
 
Firewall in Perl by Chankey Pathak
Firewall in Perl by Chankey PathakFirewall in Perl by Chankey Pathak
Firewall in Perl by Chankey Pathak
 
Moose Hacking Guide
Moose Hacking GuideMoose Hacking Guide
Moose Hacking Guide
 
Introduction to Perl MAGIC
Introduction to Perl MAGICIntroduction to Perl MAGIC
Introduction to Perl MAGIC
 
Introduction to OO Perl with Moose
Introduction to OO Perl with MooseIntroduction to OO Perl with Moose
Introduction to OO Perl with Moose
 
YAPC::Asia 2014 - 半端なPHPDisでPHPerに陰で笑われないためのPerl Monger向け最新PHP事情
YAPC::Asia 2014 - 半端なPHPDisでPHPerに陰で笑われないためのPerl Monger向け最新PHP事情YAPC::Asia 2014 - 半端なPHPDisでPHPerに陰で笑われないためのPerl Monger向け最新PHP事情
YAPC::Asia 2014 - 半端なPHPDisでPHPerに陰で笑われないためのPerl Monger向け最新PHP事情
 
Great Tools Heavily Used In Japan, You Don't Know.
Great Tools Heavily Used In Japan, You Don't Know.Great Tools Heavily Used In Japan, You Don't Know.
Great Tools Heavily Used In Japan, You Don't Know.
 
Perl.Hacks.On.Vim
Perl.Hacks.On.VimPerl.Hacks.On.Vim
Perl.Hacks.On.Vim
 
10 books that every developer must read
10 books that every developer must read10 books that every developer must read
10 books that every developer must read
 
The Programmer
The ProgrammerThe Programmer
The Programmer
 

Ähnlich wie Moose - YAPC::NA 2012

Good Evils In Perl (Yapc Asia)
Good Evils In Perl (Yapc Asia)Good Evils In Perl (Yapc Asia)
Good Evils In Perl (Yapc Asia)
Kang-min Liu
 
Rapid Development with Ruby/JRuby and Rails
Rapid Development with Ruby/JRuby and RailsRapid Development with Ruby/JRuby and Rails
Rapid Development with Ruby/JRuby and Rails
elliando dias
 

Ähnlich wie Moose - YAPC::NA 2012 (20)

Perl object ?
Perl object ?Perl object ?
Perl object ?
 
Perl: Hate it for the Right Reasons
Perl: Hate it for the Right ReasonsPerl: Hate it for the Right Reasons
Perl: Hate it for the Right Reasons
 
Lithium: The Framework for People Who Hate Frameworks
Lithium: The Framework for People Who Hate FrameworksLithium: The Framework for People Who Hate Frameworks
Lithium: The Framework for People Who Hate Frameworks
 
Moose: Perl Objects
Moose: Perl ObjectsMoose: Perl Objects
Moose: Perl Objects
 
To infinity and beyond
To infinity and beyondTo infinity and beyond
To infinity and beyond
 
(Parameterized) Roles
(Parameterized) Roles(Parameterized) Roles
(Parameterized) Roles
 
Good Evils In Perl (Yapc Asia)
Good Evils In Perl (Yapc Asia)Good Evils In Perl (Yapc Asia)
Good Evils In Perl (Yapc Asia)
 
Puppet and the HashiStack
Puppet and the HashiStackPuppet and the HashiStack
Puppet and the HashiStack
 
Perl Teach-In (part 2)
Perl Teach-In (part 2)Perl Teach-In (part 2)
Perl Teach-In (part 2)
 
Replacing "exec" with a type and provider: Return manifests to a declarative ...
Replacing "exec" with a type and provider: Return manifests to a declarative ...Replacing "exec" with a type and provider: Return manifests to a declarative ...
Replacing "exec" with a type and provider: Return manifests to a declarative ...
 
Replacing "exec" with a type and provider
Replacing "exec" with a type and providerReplacing "exec" with a type and provider
Replacing "exec" with a type and provider
 
Stanford Hackathon - Puppet Modules
Stanford Hackathon - Puppet ModulesStanford Hackathon - Puppet Modules
Stanford Hackathon - Puppet Modules
 
Rapid Development with Ruby/JRuby and Rails
Rapid Development with Ruby/JRuby and RailsRapid Development with Ruby/JRuby and Rails
Rapid Development with Ruby/JRuby and Rails
 
Postobjektové programovanie v Ruby
Postobjektové programovanie v RubyPostobjektové programovanie v Ruby
Postobjektové programovanie v Ruby
 
Reasons To Love Ruby
Reasons To Love RubyReasons To Love Ruby
Reasons To Love Ruby
 
A linguagem de programação Ruby - Robson "Duda" Sejan Soares Dornelles
A linguagem de programação Ruby - Robson "Duda" Sejan Soares DornellesA linguagem de programação Ruby - Robson "Duda" Sejan Soares Dornelles
A linguagem de programação Ruby - Robson "Duda" Sejan Soares Dornelles
 
Ruby Programming Language
Ruby Programming LanguageRuby Programming Language
Ruby Programming Language
 
jRuby: The best of both worlds
jRuby: The best of both worldsjRuby: The best of both worlds
jRuby: The best of both worlds
 
DataMapper
DataMapperDataMapper
DataMapper
 
The Zen of Lithium
The Zen of LithiumThe Zen of Lithium
The Zen of Lithium
 

Mehr von xSawyer

Mehr von xSawyer (12)

do_this and die();
do_this and die();do_this and die();
do_this and die();
 
XS Fun
XS FunXS Fun
XS Fun
 
Asynchronous Programming FTW! 2 (with AnyEvent)
Asynchronous Programming FTW! 2 (with AnyEvent)Asynchronous Programming FTW! 2 (with AnyEvent)
Asynchronous Programming FTW! 2 (with AnyEvent)
 
Asynchronous programming FTW!
Asynchronous programming FTW!Asynchronous programming FTW!
Asynchronous programming FTW!
 
Our local state, my, my - Understanding Perl variables
Our local state, my, my - Understanding Perl variablesOur local state, my, my - Understanding Perl variables
Our local state, my, my - Understanding Perl variables
 
Your first website in under a minute with Dancer
Your first website in under a minute with DancerYour first website in under a minute with Dancer
Your first website in under a minute with Dancer
 
PerlDancer for Perlers (FOSDEM 2011)
PerlDancer for Perlers (FOSDEM 2011)PerlDancer for Perlers (FOSDEM 2011)
PerlDancer for Perlers (FOSDEM 2011)
 
Perl Dancer for Python programmers
Perl Dancer for Python programmersPerl Dancer for Python programmers
Perl Dancer for Python programmers
 
When Perl Met Android (YAPC::EU 2010)
When Perl Met Android (YAPC::EU 2010)When Perl Met Android (YAPC::EU 2010)
When Perl Met Android (YAPC::EU 2010)
 
Perl Dancer on Android (first attempt)
Perl Dancer on Android (first attempt)Perl Dancer on Android (first attempt)
Perl Dancer on Android (first attempt)
 
Source Code Management systems
Source Code Management systemsSource Code Management systems
Source Code Management systems
 
Red Flags in Programming
Red Flags in ProgrammingRed Flags in Programming
Red Flags in Programming
 

Kürzlich hochgeladen

Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
panagenda
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
?#DUbAI#??##{{(☎️+971_581248768%)**%*]'#abortion pills for sale in dubai@
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 

Kürzlich hochgeladen (20)

Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
A Beginners Guide to Building a RAG App Using Open Source Milvus
A Beginners Guide to Building a RAG App Using Open Source MilvusA Beginners Guide to Building a RAG App Using Open Source Milvus
A Beginners Guide to Building a RAG App Using Open Source Milvus
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challenges
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot ModelNavi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot Model
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
 

Moose - YAPC::NA 2012

  • 2. Sawyer X blogs.perl.org/users/sawyer_x search.cpan.org/~xsawyerx metacpan.org/author/XSAWYERX github.com/xsawyerx/ „The Dancer guy!“ Projects: Dancer, Module::Starter, MetaCPAN::API, MooseX::Role::Loggable, etc.
  • 3.
  • 4.
  • 6. … but why Moose? package Person; package User; use strict; use Email::Valid; use warnings; use Moose; use Moose::Util::TypeConstraints; use Carp qw( confess ); use DateTime; extends 'Person'; use DateTime::Format::Natural; subtype 'Email'     => as 'Str' sub new {     => where { Email::Valid­>address($_) }     my $class = shift;     => message { "$_ is not a valid email      my %p = ref $_[0] ? %{ $_[0] } : @_; address" };     exists $p{name} has email_address => (         or confess 'name is a required attribute';     is       => 'rw',     $class­>_validate_name( $p{name} );     isa      => 'Email',     required => 1,     exists $p{birth_date} );         or confess 'birth_date is a required attribute';     $p{birth_date} = $class­ >_coerce_birth_date( $p{birth_date} );     $class­>_validate_birth_date( $p{birth_date} );     $p{shirt_size} = 'l'         unless exists $p{shirt_size}:     $class­>_validate_shirt_size( $p{shirt_size} );     return bless %p, $class; } sub _validate_name {     shift;     my $name = shift;     local $Carp::CarpLevel = $Carp::CarpLevel + 1;     defined $name         or confess 'name must be a string'; }
  • 8. Writing objects in basic Perl 5 Create a reference (usually to a hash) Connect it to a package (using „bless“) Provide subroutines that access the hash keys Error check the hell out of it
  • 9. Writing objects in basic Perl 5, e.g. package Dog; use strict; use warnings; sub new { my $class = shift; my $self = bless {}, $class; return $self; } 1;
  • 10. Issues Defining the same new() concept every time No parameters for new() yet Will have to do all error-checking manually
  • 12. You get use strict; use warnings; new() method To hell with ponies, you get a moose! (roll picture of a moose beating a pony in soccer)
  • 13. Full affordance accessors (attributes) has name => ( is => 'rw' ); „ro“ is available for read-only attributes You can manually change setter/getter via writer/reader Attributes can have defaults Attributes can have type constraints Attributes can have traits Attributes can be lazy, have builders, clearers, predicates...
  • 14. Type constraints has name => ( is => 'ro', isa => 'Str' ); Str, Int, Bool, ArrayRef, HashRef, CodeRef, Regex, Classes Combine: ArrayRef|HashRef, ArrayRef[Str] Derivatives (Int is a Num) Create your own using subtype, available at Moose::Util::TypeConstraints
  • 15. Methods Same as before sub run { my $self = shift; say qq{I make it a habit only to run when being chased!}; }
  • 16. Inheritance easy as... package Punk use Moose; extends 'Person'; Multiple inheritance also possible (extends accepts array) package Child; use Moose; extends qw/Father Mother/;
  • 17. Roles are even better package Punk; use Moose; with qw/Tattoos Piercings Squatter/; Roles are things you do, instead of things you are.
  • 18. More hooks than a coat rack! package User::WinterAware; use Moose; extends 'User'; before leaving => sub { my $self = shift; $self->cold and $self->take_jacket; };
  • 19. More hooks than a coat rack! package User::Secure; use Moose; extends 'User'; around login => sub { my $orig = shift; my $self = shift; $self->security_check and $self->$orig(@_); };
  • 20. More hooks than a coat rack! Before After Around Inner Augment
  • 21. Back to attributes... has set => ( is => 'rw', isa => 'Set::Object', default => sub { Set::Object->new }, required => 1, lazy => 1, predicate => 'has_set', clearer => 'clear_set',
  • 22. Attribute options: default default => 'kitteh' # string default => 3 # number default => sub { {} } # HashRef default => sub { [] } # ArrayRef default => sub { Object->new } # an Object (if you need a more elaborate sub, use builder)
  • 23. Attribute options: required required => 1 # required required => 0 # not required
  • 24. Attribute options: lazy lazy => 1 # make it lazy Class will not create the slot for this attribute unless it absolutely has to, defined by whether it is accessed at all. No access? No penalty! Lazy == good
  • 25. Attribute options: builder builder => 'build_it' # subroutine name sub build_it { my $self = shift; # not a problem! return Some::Object->new( $self- >more_opts ); }
  • 26. Attribute options: clearer clearer => 'clear_it' # subroutine name # you don't need to create the subroutine sub time_machine { my $self = shift; $self->clear_it; # 'it' never happened :) }
  • 27. Attribute options: predicate predicate => 'has_it' # subroutine name # you don't need to create the subroutine sub try_to_do_it { my $self = shift; $self->has_it && $self->do_it(); }
  • 28. Attribute options: lazy_build lazy_build => 1 # <3 # the same as: lazy => 1, builder => '_build_it', # private clearer => 'clear_it', predicate => 'has_it',
  • 29. Example: Comican A hub for various comics strips Allow you to fetch comic strips Standard uniformed interface to add more comics We'll be using: Roles Lazy attributes Overriding attributes options Attribute predicates
  • 30. Comican comic modules Comican::Comic::Dilber t interface role Comican::Comic::PennyArcade Comican::Comic::xkcd Comican:: Role::Comic main module user Comican.pm
  • 31. Comican: overall Comican.pm is the user's interface It's a hub for Comican::Comic::* modules They are objects that fetch specific comic strips They have a common interface Defined by Comican::Role::Comic
  • 32. SHOW ME THE CODE!
  • 33. /^M(?:o(?:o|[ou]se)?)?$/ Moose: standart Mouse: subset, uses XS, faster (Any::Moose: use Mouse unless Moose already loaded) Moo: Pure-Perl, subset, blazing fast Mo: As little as possible (incl. character count) M: Really as little as possible Hummus (HuMoose): Incompatible chickpeas paste
  • 34.