Here's how I like to do this:

I prefer keeping one bless in my module. I don't like having to check multiple places in the module for the blessing. I've had some headaches because of that.

I also like to think that most my modules 'use' or 'contain' a database handle. So my modules don't inherit from DBI. Instead, I opt for a the some sort of singleton factory to get a $dbh instance. There are plenty of ways to do this, here's one that I've been using.

HTH

package MyApp::Ticket; use strict; sub new { my ($class,%args) = @_; my $self = bless {}; if ( $args{ticket_number} ) { $self->load( $args{ticket_number} ); } else { $self->init(%args); } return $self; } sub init { my ($self,%args) = @_; $$self{_time} => $args{'time'}; $$self{_trade_ref} => $args{'trade_ref'}; $$self{_adr_buyer_bank} => $args{'adr_buyer_bank'}; $$self{_adr_seller_bank} => $args{'adr_seller_bank'}; $$self{_ti_seller_pays} => $args{'seller_pays'}; return $self; } sub load { my $self = shift; my $ticket_number = shift; # # pull the $dbh from some shared location # like a singleton factory # my $dbh = GetDBH(); 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; return $self->init($$row); } # # 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 $new_ticket = new MyApp::Ticket( ticket_number => 12345 );

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