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 }; }

In reply to Re: how do i implement alternate constructors for an object by kilinrax
in thread 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.