I'm trying to get my head around the way objects work in perl. I'd like to be able to manipulate a "Ticket" object, which will have various methods attached to it. But i'd like to initialize this object as either a new Ticket, or with data fields filled in from a database table. One idea was to create a separate constructor for the different cases.
package MyApp::Ticket;
use strict;
sub new {
my ($class,%args) = @_;
my $self = bless {
_time => $args{'time'},
_trade_ref => $args{trade_ref},
_adr_buyer_bank => $args{adr_buyer_bank},
_adr_seller_bank => $args{adr_seller_bank},
_seller_pays => $args{seller_pays},
}, $class;
return $self;
}
sub load {
my ($class,$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;
my $self = bless {
_time => $row->{'time'},
_trade_ref => $row->{trade_ref},
_adr_buyer_bank => $row->{adr_buyer_bank},
_adr_seller_bank => $row->{adr_seller_bank},
_seller_pays => $row->{seller_pays},
}, $class;
return $self;
}
and then initialize tickets like so:
my $new_ticket = new MyApp::Ticket(
time=>time(),trad_ref=>34567,
adr_buyer_bank => 'blah',
adr_seller_bank =>'blah,
seller_pays => 99.99
);
my $old_ticket = MyApp::Ticket->load(12345);
I'm not quite sure if that would work, and it seems kind of messy. Another idea I had was to define separate constructors in DBTicket and NewTicket classes, and simply inherit all the common methods from the regular Ticket class. Perhaps that would be cleaner? Any advice would be appreciated.