SlideShare a Scribd company logo
1 of 23
Moose A postmodern metaclass-based object system for Perl 5
Moose Sawyer X * blogs.perl.org/users/sawyer_x *  search.cpan.org/~xsawyerx/ * search.metacpan.org/#/author/XSAWYERX * github.com/xsawyerx
Objects in Perl 5 (a short intro) ,[object Object]
Manual  new()  method
No real attributes bless {}, __PACKAGE__; sub new { my ( $class, @args ) =  @_; my $self = { @args }; # params bless $self, $class; return $self; } sub name { my ( $self, $name ) = @_; $name and $self->{'name'} = $name; return $self->{'name'}; }
Why would you want to use Moose? Moose package Person; use strict; use warnings; use Carp qw( confess ); use DateTime; use DateTime::Format::Natural; sub new { my $class = shift; my %p = ref $_[0] ? %{ $_[0] } : @_; exists $p{name} or confess 'name is a required attribute'; $class->_validate_name( $p{name} ); 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'; } Plain old Perl 5 package User; use Email::Valid; use Moose; use Moose::Util::TypeConstraints; extends 'Person'; subtype 'Email' => as 'Str' => where { Email::Valid->address($_) } => message { "$_ is not a valid email address" }; has email_address => ( is  => 'rw', isa  => 'Email', required => 1, );
Get it?
Defining an object in Moose ,[object Object]
use warnings
An object!
new()  method
A pon-.. err.. a moose! package User; use Moose; 1; You get:
Full-Affordance accessors ,[object Object]
You can set the getter or setter manually via  reader / writer
I'll show more attribute options later on has name => ( is => 'rw', );
An attribute with type constraint ,[object Object]
You can combine:  ArrayRef[Str] ,  HashRef[ArrayRef[Int]]
They have inheritance:  Int  is a  Num
Roll your own using  subtype package User; use Moose; has name => ( is  => 'rw', isa => 'Str', ); 1;
Methods are the same as before sub method { my $self = shift; ... $self->more(); }
Inheritance is as easy as... ,[object Object],package Punk; use Moose; extends 'Person'; 1; package Child; use Moose; extends qw/ Father Mother /; 1;
Roles are even easier! ,[object Object],package Punk; use Moose; extends 'Person'; with 'Piercings'; 1; package Punk; use Moose; extends 'Person'; with qw/ Piercings Tattoos /; 1;
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; }; 1; ,[object Object]

More Related Content

What's hot

From mysql to MongoDB(MongoDB2011北京交流会)
From mysql to MongoDB(MongoDB2011北京交流会)From mysql to MongoDB(MongoDB2011北京交流会)
From mysql to MongoDB(MongoDB2011北京交流会)
Night Sailer
 
Introducing Assetic (NYPHP)
Introducing Assetic (NYPHP)Introducing Assetic (NYPHP)
Introducing Assetic (NYPHP)
Kris Wallsmith
 

What's hot (20)

Moose workshop
Moose workshopMoose workshop
Moose workshop
 
WordPress Cuztom Helper
WordPress Cuztom HelperWordPress Cuztom Helper
WordPress Cuztom Helper
 
To infinity and beyond
To infinity and beyondTo infinity and beyond
To infinity and beyond
 
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
 
Doctrine MongoDB ODM (PDXPHP)
Doctrine MongoDB ODM (PDXPHP)Doctrine MongoDB ODM (PDXPHP)
Doctrine MongoDB ODM (PDXPHP)
 
The effective use of Django ORM
The effective use of Django ORMThe effective use of Django ORM
The effective use of Django ORM
 
The jQuery Divide
The jQuery DivideThe jQuery Divide
The jQuery Divide
 
Django - 次の一歩 gumiStudy#3
Django - 次の一歩 gumiStudy#3Django - 次の一歩 gumiStudy#3
Django - 次の一歩 gumiStudy#3
 
A Few of My Favorite (Python) Things
A Few of My Favorite (Python) ThingsA Few of My Favorite (Python) Things
A Few of My Favorite (Python) Things
 
From mysql to MongoDB(MongoDB2011北京交流会)
From mysql to MongoDB(MongoDB2011北京交流会)From mysql to MongoDB(MongoDB2011北京交流会)
From mysql to MongoDB(MongoDB2011北京交流会)
 
Keeping It Small with Slim
Keeping It Small with SlimKeeping It Small with Slim
Keeping It Small with Slim
 
Introduction to Perl Best Practices
Introduction to Perl Best PracticesIntroduction to Perl Best Practices
Introduction to Perl Best Practices
 
WordPress London 16 May 2012 - You don’t know query
WordPress London 16 May 2012 - You don’t know queryWordPress London 16 May 2012 - You don’t know query
WordPress London 16 May 2012 - You don’t know query
 
Puppet Camp DC 2015: Stop Writing Puppet Modules: A Guide to Best Practices i...
Puppet Camp DC 2015: Stop Writing Puppet Modules: A Guide to Best Practices i...Puppet Camp DC 2015: Stop Writing Puppet Modules: A Guide to Best Practices i...
Puppet Camp DC 2015: Stop Writing Puppet Modules: A Guide to Best Practices i...
 
Introducing Assetic (NYPHP)
Introducing Assetic (NYPHP)Introducing Assetic (NYPHP)
Introducing Assetic (NYPHP)
 
Advanced symfony Techniques
Advanced symfony TechniquesAdvanced symfony Techniques
Advanced symfony Techniques
 
Bioinformatics p5-bioperl v2013-wim_vancriekinge
Bioinformatics p5-bioperl v2013-wim_vancriekingeBioinformatics p5-bioperl v2013-wim_vancriekinge
Bioinformatics p5-bioperl v2013-wim_vancriekinge
 
Bioinformatica p6-bioperl
Bioinformatica p6-bioperlBioinformatica p6-bioperl
Bioinformatica p6-bioperl
 
Ant
Ant Ant
Ant
 

Similar to Moose talk at FOSDEM 2011 (Perl devroom)

Writing Friendly libraries for CodeIgniter
Writing Friendly libraries for CodeIgniterWriting Friendly libraries for CodeIgniter
Writing Friendly libraries for CodeIgniter
CodeIgniter Conference
 
Decorators in Python
Decorators in PythonDecorators in Python
Decorators in Python
Ben James
 
Render API - Pavel Makhrinsky
Render API - Pavel MakhrinskyRender API - Pavel Makhrinsky
Render API - Pavel Makhrinsky
DrupalCampDN
 
Introduction to Perl - Day 2
Introduction to Perl - Day 2Introduction to Perl - Day 2
Introduction to Perl - Day 2
Dave Cross
 

Similar to Moose talk at FOSDEM 2011 (Perl devroom) (20)

Perl Teach-In (part 2)
Perl Teach-In (part 2)Perl Teach-In (part 2)
Perl Teach-In (part 2)
 
Moose - YAPC::NA 2012
Moose - YAPC::NA 2012Moose - YAPC::NA 2012
Moose - YAPC::NA 2012
 
Modern Perl
Modern PerlModern Perl
Modern Perl
 
Constructive Destructor Use
Constructive Destructor UseConstructive Destructor Use
Constructive Destructor Use
 
Writing Friendly libraries for CodeIgniter
Writing Friendly libraries for CodeIgniterWriting Friendly libraries for CodeIgniter
Writing Friendly libraries for CodeIgniter
 
HTML::FormHandler
HTML::FormHandlerHTML::FormHandler
HTML::FormHandler
 
Drupal Lightning FAPI Jumpstart
Drupal Lightning FAPI JumpstartDrupal Lightning FAPI Jumpstart
Drupal Lightning FAPI Jumpstart
 
JQuery Basics
JQuery BasicsJQuery Basics
JQuery Basics
 
What's New in ZF 1.10
What's New in ZF 1.10What's New in ZF 1.10
What's New in ZF 1.10
 
PHP Unit Testing
PHP Unit TestingPHP Unit Testing
PHP Unit Testing
 
Decorators in Python
Decorators in PythonDecorators in Python
Decorators in Python
 
Render API - Pavel Makhrinsky
Render API - Pavel MakhrinskyRender API - Pavel Makhrinsky
Render API - Pavel Makhrinsky
 
Perl object ?
Perl object ?Perl object ?
Perl object ?
 
Writing Pluggable Software
Writing Pluggable SoftwareWriting Pluggable Software
Writing Pluggable Software
 
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
 
Further Php
Further PhpFurther Php
Further Php
 
Javascript Primer
Javascript PrimerJavascript Primer
Javascript Primer
 
Exploiting Php With Php
Exploiting Php With PhpExploiting Php With Php
Exploiting Php With Php
 
Advanced JavaScript
Advanced JavaScriptAdvanced JavaScript
Advanced JavaScript
 
Introduction to Perl - Day 2
Introduction to Perl - Day 2Introduction to Perl - Day 2
Introduction to Perl - Day 2
 

More from xSawyer

More from 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
 

Recently uploaded

+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@
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Victor Rentea
 
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
 

Recently uploaded (20)

Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf
 
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
 
+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...
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectors
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with Milvus
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
 
Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024
 
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
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
 
Ransomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfRansomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdf
 
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
 
CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistan
 
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
 
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...
 
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
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 

Moose talk at FOSDEM 2011 (Perl devroom)

  • 1. Moose A postmodern metaclass-based object system for Perl 5
  • 2. Moose Sawyer X * blogs.perl.org/users/sawyer_x * search.cpan.org/~xsawyerx/ * search.metacpan.org/#/author/XSAWYERX * github.com/xsawyerx
  • 3.
  • 4. Manual new() method
  • 5. No real attributes bless {}, __PACKAGE__; sub new { my ( $class, @args ) = @_; my $self = { @args }; # params bless $self, $class; return $self; } sub name { my ( $self, $name ) = @_; $name and $self->{'name'} = $name; return $self->{'name'}; }
  • 6. Why would you want to use Moose? Moose package Person; use strict; use warnings; use Carp qw( confess ); use DateTime; use DateTime::Format::Natural; sub new { my $class = shift; my %p = ref $_[0] ? %{ $_[0] } : @_; exists $p{name} or confess 'name is a required attribute'; $class->_validate_name( $p{name} ); 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'; } Plain old Perl 5 package User; use Email::Valid; use Moose; use Moose::Util::TypeConstraints; extends 'Person'; subtype 'Email' => as 'Str' => where { Email::Valid->address($_) } => message { "$_ is not a valid email address" }; has email_address => ( is => 'rw', isa => 'Email', required => 1, );
  • 8.
  • 12. A pon-.. err.. a moose! package User; use Moose; 1; You get:
  • 13.
  • 14. You can set the getter or setter manually via reader / writer
  • 15. I'll show more attribute options later on has name => ( is => 'rw', );
  • 16.
  • 17. You can combine: ArrayRef[Str] , HashRef[ArrayRef[Int]]
  • 18. They have inheritance: Int is a Num
  • 19. Roll your own using subtype package User; use Moose; has name => ( is => 'rw', isa => 'Str', ); 1;
  • 20. Methods are the same as before sub method { my $self = shift; ... $self->more(); }
  • 21.
  • 22.
  • 23.
  • 24. after
  • 25.
  • 26. after
  • 28. inner
  • 30. Back to attributes options... has set => ( is => 'rw', isa => 'Set::Object', default => sub { Set::Object->new }, required => 1, lazy => 1, predicate => 'has_set', clearer => 'clear_set', builder => 'build_set', );
  • 31. Attribute options default => 'kitteh', # string default => 3, # number default => sub { {} }, # HashRef default => sub { [] }, # ArrayRef default => sub { Object->new }, # an Object etc. etc. (if you need a more elaborate sub, use builder ) default
  • 32. Attribute options required => 1, # required required => 0, # not required required
  • 33. Attribute options lazy => 1, # make it lazy Class will not create the slot for this attribute unless it absolutely has to. That is defined by whether it is accessed at all. Wasn't accessed? You don't pay the penalty! :) lazy = good lazy
  • 34. Attribute options builder => 'build_it', # subroutine name sub build_it { my $self = shift; # not a problem! return Some::Object->new( $self->more_opts, ); } # and, obviously... after build_it => sub { “they will come” }; (a builder sets the value of the attribute) builder
  • 35. Attribute options 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 :) } (a clearer clears the value, as if it never existed) (does not go back to default) clearer
  • 36. Attribute options 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(); } (a predicate checks an attribute value exists) (even false values) (which is good!) predicate
  • 37. Attribute options lazy_build => 1, # <3 # the same as: lazy => 1, builder => '_build_it', # private clearer => 'clear_it', predicate => 'has_it', ( lazy_build is recommended) lazy_build
  • 38.
  • 41. It's here to stay
  • 42.
  • 50. ... sub { goto CPAN; }