Beefy Boxes and Bandwidth Generously Provided by pair Networks
Don't ask to ask, just ask
 
PerlMonks  

Re: Class::dbi::loader and OO structure

by trs80 (Priest)
on Apr 21, 2003 at 01:22 UTC ( #251904=note: print w/ replies, xml ) Need Help??


in reply to Class::dbi::loader and OO structure

I am preparing to post a more detailed intro to Class::DBI, but your post came just as I was doing the initial walk through of the very same thing. Here is how I resolved the problem, but this will likely be refined further. I was unable to get the Class::DBI::Loader module to work correctly so this code had a two fold value for me. This first part is in your initial Class file, the one that defines the DBI connection parameters.

package My::ClassDBI; use strict; use warnings; use base 'Class::DBI'; my $dsn = 'dbi:mysql:database'; my $user = 'user'; my $password = 'password'; My::ClassDBI->set_db('Main', $dsn, $user, $password); # auto load tables my $base = __PACKAGE__; # "My::ClassDBI"; # create connection to database my $dbh = DBI->connect($dsn,$user,$password) or die $DBI::errstr; # not the Right Way(tm) but works for now my $get_tables = $dbh->prepare(qq!SHOW TABLES!); $get_tables->execute; my @tables; while ( my $table = $get_tables->fetchrow ) { my @columns; my $ucftable = ucfirst($table); my $get_column = $dbh->prepare(qq!DESC $table!); $get_column->execute(); while ( my @cols = $get_column->fetchrow() ) { # force the primary key to be first # this insures Class::DBI correctly relates table # without having to manually define the Primary Key $cols[3] =~ /pri/i ? unshift @columns , $cols[0] : push @columns , $cols[0] } eval qq!package $ucftable; use base '$base'; $ucftable->table('$table'); $ucftable->columns(All => qw/! . join(" ",@columns) . "/);"; } # Table1 and Table 2 class dynamically generated above Table1->has_many('method_name_you_want' , Table2 => 'related_column' ); 1;

Then inside your application you simply use My::ClassDBI and all your classes (tables) are sub classed under it.
use My::ClassDBI; use strict; # you can place the has_many here or in the # package as shown above # Table1->has_many('method_name_you_want' , # Table2 => 'related_column' ); my $row_from_table1 = Table1->retrieve(1); my @table2_objects = $row_from_table1->method_name_you_want; foreach (@table2_objects) { print $_->column_name , "\n"; } 1;


Comment on Re: Class::dbi::loader and OO structure
Select or Download Code

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://251904]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others perusing the Monastery: (5)
As of 2015-07-05 08:48 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    The top three priorities of my open tasks are (in descending order of likelihood to be worked on) ...









    Results (61 votes), past polls