You don't have to use Class::DBI as mentioned above, (i.e. you could just use DBI in the parent object) but that would be my way of doing it. For example you have WebApp::DBI (which is use base 'Class::DBI'). Then WebApp::User and WebApp::Company are both use base 'WebApp::DBI'. In WebApp::DBI I have a getdbh subroutine so all classes and objects inherit a ->getdbh method.
package WebApp::DBI; use base 'Class::DBI'; use DBD::mysql; use Site; # where I store db account info WebApp::DBI->set_db('Main', "DBI:mysql:database=$dbname;host=$hostname;port=$port", $dbusername, $dbpassword); # you can say __PACKAGE__ instead of "WebApp::DBI" WebApp::DBI->add_constructor(all_reverse_by_id => '1=1 ORDER BY id DESC'); # a query inherited by all objects sub getdbh { # so we don't have to set up our own # db_Main subroutine that would return a dbh my @dbhandles = WebApp::DBI->db_handles; # I use Ima::DBI->db_handles which Class::DBI # inherits instead of making a sub db_Main # as Class::DBI suggests, I'm wierd. my $dbh = $dbhandles[0]; $dbh->{RaiseError} = 1; return $dbh; } 1;
With this approach I believe you only need to use an object in a subroutine that needs it, otherwise the module is not loaded. Also objects inheriting from Class::DBI load columns lazily based on definitions of Essential columns.
Also note that you can put generic retrieval code in the parent module (or in that parent's parent as with Class::DBI which provides the retrieve method) and then just do special cases in the child modules.
Hope this helps. So bottom line is, for all this to be easily cleared up why not read the Class::DBI perldoc a few times and as rhesa notes you can get the db handle from its connection method or better yet as they recommend override db_Main with your own settings.
In reply to Re: How can I avoid creating two instances of the same object
by mattr
in thread How can I avoid creating two instances of the same object
by beachguy82
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |