Mouse and Moose in Perl - Walking in a winter wonderland... kinda

I like Moose but I work heavily in non-persistent applications. Sadly this makes Moose's start up expense too much.

But recently I revisited Mouse (thanks to a friend). The last time I looked at it, I misread the documentation and it sounds like it was no longer being supported by the original developer. But not anymore, w00t!

The one part I really like about Mouse (and Moose) is the declarative nature of creating accessors (and therefore attributes). I really like this because it reduces the number of simple accessor tests that you need to write (saving time, tendium and kittens).

I used to use Class::Accessor but I always ran into inheritance and validation issues (which I used Params::Validate but this caused lots of custom magic for inheritance).

I think the Mouse/Moose syntax is significantly cleaner.

Compare Class::Accessor:
package User;

use strict;
use warnings;

use Carp;

use base qw( Class::Accessor );

__PACKAGE__->mk_accessors( qw( id username password first_name last_name ) );

# override new since I really don't like the hash ref creator and I want validation
sub new {
   my $class = shift;
   my $self  = $class->SUPER::new;

   return $self->_init( @_ );

# does init and validation
sub _init {
   my $self = shift;
   my %p    = validate @_, { # wrap in sub to override in inheritance so ugly 
                  id => 1, username => 1, first_name => 1, last_name => 1};
   # init them here

vs Mouse:
package User;

use Mouse; # includes strict and warnings

use Carp;
use English qw( -no_match_vars );

has 'id'       => ( is => 'ro' );
has 'username' => ( is => 'rw' );
has 'password' => ( is => 'rw' ); 
has 'first_name'   => ( is => 'rw', isa => 'Str' );
has 'last_name'    => ( is => 'rw', isa => 'Str');

no Mouse;

Plus the super great lazy_build option which is perfect for database handles and such.


Popular posts from this blog

Template Toolkit Debugging inside of Perl Dancer

BootstrapX clickover

Please don't create tests like this in Perl