Dear Monks
I have been writing many objects for a while and most of them fall into the general pattern of simply wrapping a mySQL table. They load a record from the table put the variables into the object hash and then get and set functions manipulate the data and provide input correctness and output formatting.
I did this previously by every field having a get and set method which got the data from the database or wrote directly to the database. It worked but it is not very efficient.
Basically my code consisted of many many verions of this:
sub get_user_name( $ ) { my $data; my $query; my $self = shift; my $dbh = $self->{'dbh'}; my $sqlQuery = "SELECT UserName FROM USERINFORMATION WHERE UserID = \'$self->{user_id}\'"; $query = $dbh->prepare( $sqlQuery ); $query-> execute() || die $dbh->errstr; if( $data = $query->fetchrow_array() ) { $self->{'error_type'} = ""; $self->{'error_string'} = ""; return( $data ); } else { $self->{'error_type'} = "variable returned no value"; $self->{'error_string'} = "variable returned no value"; return( undef ); } } sub update_user_name( $ ) { my @data; my $query; my $self = shift; my $dbh = $self->{'dbh'}; # Test for zero length input and if( $_[0] eq "" ) { $self->{'error_type'} = "blank"; $self->{'error_string'} = "This variable must be filled in."; return( undef ); } # test for input string being too long elsif( length( $_[0] ) > 20 ) { $self->{'error_type'} = "overlength"; $self->{'error_string'} = "This variable may only be 20 characte +rs."; return( undef ); } # test for chracter correctness elsif( $_[0] =~ /[^A-Za-z0-9_]/ ) { $self->{'error_type'} = "illegal characters"; $self->{'error_string'} = "Only the chracters A-Z a-z 0-9 _ are +allowed."; return( undef ); } # test for variable specific cases here # username must be unique my $sqlQuery = "SELECT UserID, UserName FROM USERINFORMATION WHERE UserName = \'$_[0]\'"; my $query = $dbh->prepare( $sqlQuery ); $query->execute() || die $dbh->errstr; @data = $query->fetchrow_array(); #if the userid of the duplicate groupname #matches the current userid of the person #registering the system then proceed if( $data[0] != $self->{'user_id'} && $data[1] ne "" ) { $self->{'error_type'} = "not unique"; $self->{'error_string'} = "User Name already in use please cho +ose another."; return( undef ); } else { my $update = &format_for_mysql( $_[0] ); my $sqlQuery = "UPDATE USERINFORMATION SET UserName = \'$update\' WHERE UserID = $self->{user_id}"; $query = $dbh->do( $sqlQuery ); return( 1 ); } }
Now I wonder since 90 percent of my objects simply wrap a table like the above code is there a better way?
Edit by tye, add READMORE tag
In reply to Writing Better Objects by Angel
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |