dr_death has asked for the wisdom of the Perl Monks concerning the following question:

Hello all,

I am pretty new to OOP programming and am trying to learn how to use Moose and I cant seem to find an example/explanation of what I need to do, although I am learning a lot reading through trying to find it.

What I am trying to do is create a new object like below and then have that return an ID from a DB.

get_id->new( email => 'test@test.com' );

I have something like the below already;

has 'email' => ( is => 'rw', isa => 'Str', required => 1, clearer => 'clear_email', predicate => 'has_email', );

I've seen 'default => sub', but I'm not entirely sure if it's appropriate or how the inheritance works using it.

Is there someway I can call a sub or method and have it return the ID? If so, could you please tell me where I can find it in the documentation?

Thanks for your help!

Replies are listed 'Best First'.
Re: How do I process then return something in Moose?
by 1nickt (Canon) on Feb 07, 2017 at 12:57 UTC

    Hi dr_death,

    I personally use Moo rather than Moose as I find the latter has lots of power tools I never need. However, I believe the answer is mostly the same for the two systems. You probably want to use default or builder as described at http://search.cpan.org/~ether/Moose-2.2004/lib/Moose/Manual/Attributes.pod#Default_and_builder_methods. Since you'll presumably need one of the other attributes to use in the DB query, you'll probably have to make the attribute lazy and use builder. Something like:

    has 'email' => ( is => 'rw', isa => 'Str', lazy => 1, builder => '_lookup_email', ); sub _lookup_email { my $self = shift; return $self->_dbh->selectall_array( 'select email from users where name = ?', {}, $self->name, )->[0]; );
    Obviously you'll have to supply the DB connection, error handling if the email is not found, etc. Also note that the Moo[se] Type libraries should be able to provide an email address type, so your isa could be email or similar and the value will be checked.

    Edit: On re-reading I see that you maybe want to supply the email address and return the DB ID after adding a record? If so, just change the builder sub to do what you want!

    Hope this helps!


    The way forward always starts with a minimal test.