go ahead... be a heretic | |
PerlMonks |
Re: Code factoryby blue_cowdawg (Monsignor) |
on Jul 08, 2003 at 22:12 UTC ( [id://272495]=note: print w/replies, xml ) | Need Help?? |
What I've standardized on for my database type applications is a series of object oriented modules that get extended by (for a lack of better term) child modules.
The Data ObjectLet's start with the dataObj module. I mentioned in another thread that I keep my database and other generic information in another module and I'll hand wave that here.package dataObj; use dbConf; # This module has the db connect info my $connected=0; # this rarely gets actually invoked. sub new { my $proto=shift; my $class = ref($proto)|| $proto; my $self = { dbh=> undef, sth=> undef ... and other goodies } bless $self,$class; $self->connect2db if not $connected; return $self; } sub connect2db { my $self=shift; my $method=( $_[0] ? $_[0] : "oracle"); my $config=new dbConfig($method); # The connectParms method of dbConfig returns an # array with the DSN, LOGIN and PASSWORD info $self->{dbh} = DBI->connect($config->connectParms) or die "Could not connect " . $DBI::errstr; } sub prepare { my $self=shift; my $sql=shift; die "Preapre without connect!" if not $connected; $self->{sth}=$self->{dbh}->prepare($sql) or die "Could not prepare\n" . $sql . "\n" . $self->{dbh}->errstr; } sub execute { my $self=shift; return if not $self->{sth}; $self->{sth}->execute(@_); } .... and so on... 1; CAVEAT:The above code is just to get the idea across and is not to be considered prime time code I would then "overload" the module with the data object in question. Presumably I would put methods into the data object that deal with types and such intelligently Example: package dataObj::contactInfo; use vars qw/ @ISA /; use dataObj; @ISA=qq(dataObj); sub new { my $proto=shift; my $class=ref($proto)||$proto; my $self= { name => undef, email => undef }; bless $self,$class; $self->connect2db("mysql1"); return $self; } sub get_contact_by_name { my ($self,$name)=@_; return if not $name; $self->prepare("select email from contacts where name= ?"); $self->execute($name); my $vals=$self->fetchrow_hashref ...blah...blah....blah... 1; Hopefully you get the idea.
In Section
Seekers of Perl Wisdom
|
|