Beefy Boxes and Bandwidth Generously Provided by pair Networks
more useful options

Re: Learning Moose, and have a few questions.

by tobyink (Abbot)
on May 13, 2013 at 12:36 UTC ( #1033288=note: print w/replies, xml ) Need Help??

in reply to Learning Moose, and have a few questions.

"There's a new Moose way of creating constructors, and defining what paramaters (arguments, options) those accept. Is there a Moose way to define subroutine parameters?"

No, but see MooseX::Method::Signatures, MooseX::Declare, etc.

"I've defined the attributes for my class... how do I deal with attributes of the object (i.e., self) that are objects from a different module?"

Maybe you want to be using lazy builders, and allowing for dependency injection...

package Example; use Moose; use Net::LDAP; # Options related to SSH has [qw( host user )] => ( is => "ro", isa => "Str", required => 1, ); has ldap_class => ( is => "ro", builder => "_build_ldap_class", ); has ldap => ( is => "ro", lazy => 1, builder => "_build_ldap", ); has error => ( is => "rw", isa => "Str", ); sub _build_ldap_class { return "Net::LDAP"; } sub _build_ldap { my $self = shift; return $self->ldap_class->new( $self->host ); } sub get_user { my $self = shift; my $user = $self->user; my $host = $self->host; my $mesg = $self->ldap->bind; $mesg = $self->ldap->search(filter => "(uid=$user)"); ... }

Now if somebody using your class wants to change how it does LDAP searches, they can create a subclass of Net::LDAP and do:

my $eg = Example->new(ldap_class => "Net::MyLDAP", ...);

... and your Example class will magically use their subclassed Net::LDAP object.

package Cow { use Moo; has name => (is => 'lazy', default => sub { 'Mooington' }) } say Cow->new->name

Replies are listed 'Best First'.
Re^2: Learning Moose, and have a few questions.
by walkingthecow (Friar) on May 13, 2013 at 12:45 UTC
    That is so cool! Thank you! I'm reading the documentation for Moose, as well as the Modern Perl chapter on Objects, and I don't really see anything like what you've just shown me. Personally, I think your example should be part of the docs, and the example above as well. Thanks again :)

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://1033288]
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others contemplating the Monastery: (5)
As of 2018-01-20 09:20 GMT
Find Nodes?
    Voting Booth?
    How did you see in the new year?

    Results (226 votes). Check out past polls.