Beefy Boxes and Bandwidth Generously Provided by pair Networks
We don't bite newbies here... much

OO Coding - way to make it "save" the values?

by ultranerds (Friar)
on Jul 27, 2011 at 11:52 UTC ( #917001=perlquestion: print w/replies, xml ) Need Help??
ultranerds has asked for the wisdom of the Perl Monks concerning the following question:

Hi, I'm just having a play around to build my own file, which would let me have easy access to running SQL commands (without having to do long winded DBI coding). This isn't a necessity, but more of a "project" I just wanted to do, to get a bit of experience with writing my own OO module. Here is what I have in
#!/usr/bin/perl use strict; use warnings; use DBI; use DBD::mysql; package AndySQL; sub new { my $self = {}; bless $self, "AndySQL"; my ($ignore,$user,$pass,$host,$port,$database,$debug) = @_; $self->{connect} = DBI->connect("dbi:mysql:$database:localhost:33 +06", $user, $pass) || die $DBI::errstr; $self->{debug} = $debug; return $self; } sub disconnect { } sub table { my ($self,$table) = @_; $self->{table} = $table; return $self; } sub select_options { my ($self,$opts) = @_; $self->{select_options} = $opts; return $self; } sub count { my ($self,$args) = @_; $self->{table} || die "No table defined!"; my $select_options = $self->{select_options} || ''; my @cond_vals; my @cond_fields; if (ref $args eq "HASH") { map { push @cond_fields, "$_ = ?"; push @cond_vals, $args->{$_}; } keys %$args; } my ($cond_string,$query); if ($cond_fields[0]) { $cond_string = "WHERE " . join " AND ", @cond_fields; $query = qq|SELECT COUNT(*) FROM $self->{table} $cond_string $ +select_options|; } else { $query = qq|SELECT COUNT(*) FROM $self->{table} $select_option +s|; } print "Query: $query \n" if $self->{debug}; my $sth = $self->{connect}->prepare($query); $sth->execute(@cond_vals); my $total = $sth->fetchrow() || 0; $sth->finish(); return $total; } sub select { } sub delete { } sub do_query { } 1;
Then in test.cgi:
#!/usr/bin/perl use strict; use warnings; use AndySQL; # CONFIG VARIABLES my $database = "blog_counter"; my $host = "localhost"; my $port = "3306"; my $user = "dev"; my $pass = "123foobar84!?"; my $DB = AndySQL->new($user,$pass,$host,$port,$database,1); my $tbl = $DB->table('Page_Counter'); $tbl->select_options("LIMIT 50"); my $total = $tbl->count(); print "Total found: $total \n"; my $tbl2 = $DB->table('Testing'); $tbl2->select_options("LIMIT 50"); my $total = $tbl2->count(); print "Total found: $total \n"; my $total2 = $tbl->count(); print "Total found: $total2 \n";
This works to a point. The first 2 run ok, but then when I go back and try to use $tbl, the "table" gets reset back to the first one ("Page_Counter"). How can I make it so that I can re-use the Page_Counter table, even after setting a new value in the 2nd function? Hopefully that makes sense ;) TIA! Andy

Replies are listed 'Best First'.
Re: OO Coding - way to make it "save" the values?
by moritz (Cardinal) on Jul 27, 2011 at 11:56 UTC
    sub table { my ($self,$table) = @_; $self->{table} = $table; return $self; }

    Since this method returns $self, both $tbl1 and $tbl2 are actually the same object.

    A good solution would be to distinguish between database and table objects. Or use DBIx::Class right away.


      Thanks. I don't really wanna use another DBI module, as I wanna try and play around with how this OO stuff works :) (as I said, its only a personal project). Gonna have a look at a way to distingish between the tables now

      Thanks for the reply


        Here is hint

        sub table { return AndySQL::Table->new( db => shift, tablename => shift ); }

        ultranerds, I highly suggest a reading of Beginning Perl Chapter 11: Object-Oriented Perl, followed by the Objects chapter of Modern Perl

      Mmm, I'm struggling to come up with a way to do this. Any pointers?


Re: OO Coding - way to make it "save" the values?
by zentara (Archbishop) on Jul 27, 2011 at 17:06 UTC
    Try the first entry from perldoc -q clear. It may be what you are looking for, or at least yield a clue.
    Found in /usr/lib/perl5/5.14.1/pod/perlfaq7.pod How do I clear a package? Use this code, provided by Mark-Jason Dominus: sub scrub_package { no strict 'refs'; my $pack = shift; die "Shouldn't delete main package" if $pack eq "" || $pack eq "main"; my $stash = *{$pack . '::'}{HASH}; my $name; foreach $name (keys %$stash) { my $fullname = $pack . '::' . $name; # Get rid of everything with that name. undef $$fullname; undef @$fullname; undef %$fullname; undef &$fullname; undef *$fullname; } } Or, if you're using a recent release of Perl, you can just use +the Symbol::delete_package() function instead.

    I'm not really a human, but I play one on earth.
    Old Perl Programmer Haiku ................... flash japh

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://917001]
Approved by Corion
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others drinking their drinks and smoking their pipes about the Monastery: (4)
As of 2018-06-20 02:09 GMT
Find Nodes?
    Voting Booth?
    Should cpanminus be part of the standard Perl release?

    Results (116 votes). Check out past polls.