Beefy Boxes and Bandwidth Generously Provided by pair Networks
go ahead... be a heretic
 
PerlMonks  

Re: how do i implement alternate constructors for an object

by kilinrax (Deacon)
on May 07, 2003 at 17:07 UTC ( #256304=note: print w/replies, xml ) Need Help??


in reply to how do i implement alternate constructors for an object

You could certainly implement an inheritance heirarchy to make the code cleaner. However, a simpler solution might be to pass the db handle and ticket number as args, check for their existence, and have the 'new' constructor call 'load' with them as arguments if they are:
package MyApp::Ticket; use strict; my @_args = qw( time trade_ref adr_buyer_bank adr_seller_bank seller_p +ays ); my @_atts = map { '_' . $_ } @_args; sub new { my ($class, %args) = @_; my $self = bless {}, $class; # if constructor has been passed a db handle and a ticket number, # get attributes from database. otherwise, get them from args my ($dbh, $ticket) = @args{ qw( dbh ticket ) }; if( $dbh && $ticket ) { $self->load( $dbh, $ticket ); } else { @{$self}{ @_atts } = @args{ @_args }; } return $self; } sub load { my ($self, $dbh, $ticket_number) = @_; my $sql = "SELECT * FROM tickets WHERE id = ?"; my $sth = $dbh->prepare($sql) or die $dbh->errstr; $sth->execute($ticket_number); my $row = $sth->fetchrow_hashref; @{$self}{ @_atts } = @row{ @_args }; }

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others musing on the Monastery: (6)
As of 2022-01-20 22:47 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    In 2022, my preferred method to securely store passwords is:












    Results (57 votes). Check out past polls.

    Notices?