Beefy Boxes and Bandwidth Generously Provided by pair Networks
The stupid question is the question not asked
 
PerlMonks  

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


Comment on Re: Learning Moose, and have a few questions.
Select or Download Code
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?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://1033288]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others surveying the Monastery: (12)
As of 2015-07-28 10:23 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    The top three priorities of my open tasks are (in descending order of likelihood to be worked on) ...









    Results (254 votes), past polls