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.

In reply to how do i implement alternate constructors for an object by thunders

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.