But that's seems like a lot of extra typing:
Then in any part of your code where you use the database handle you
can say
sub foo {
my ($foo, $bar) = @_;
my $dbh = Project::DB::Handle->new;
my $sth = $dbh->prepare(...);
I started out with an HTML::Mason where I've shared $dbh via
httpd.conf. I want to turn many of the Mason components into a
module (my first module actually...). So I have a lot of code like
this:
...
my @array=$dbh->selectrow_array(qq{SELECT something....}); # $dbh
is global
do something more...
...
...
So I don't want to change the code much.
What I've done (not REALLY knowing what I'm doing) is this:
{
package RD;
use strict;
our $dbh=\$HTML::Mason::Commands::dbh; # I can't use it directly
because it hasn't been created yet,
# if I could assign to $dbh in httpd.conf that might work
(not sure).
# So I use a reference and change all my $dbh to $$dbh
sub getsomething { my @array=$$dbh->selectrow_array(qq{SELECT
something....}); }
...
1;
}
I'm sure there is a better way, but this seems like less typing.
httpd.conf:
PerlAddVar MasonAllowGlobals $dbh
Then I do this in my mason code:
$dbh=WHA::Connect();
Thanks for your advice. I need it...
Ryan
On Feb 20, 2006, at 3:49 PM, Chas Owens wrote:
On 2/20/06, The Ghost <[EMAIL PROTECTED]> wrote:
I have defined $dbh (a database handle) as a global variable. I have
a module, RD, that needs access to the database. How can I use $dbh
within the RD module?
The best way to handle this is to create a singleton object to hold
the database connection instead of using a global variable. First
create a module named Project::DB::Handle.
package Project::DB::Handle;
our $dbh;
use DBI;
sub new {
return $dbh if $dbh;
$dbh = DBI->connect(...);
}
Then in any part of your code where you use the database handle you
can say
sub foo {
my ($foo, $bar) = @_;
my $dbh = Project::DB::Handle->new;
my $sth = $dbh->prepare(...);
#etc.
}
If you want to get fancy then you can create parameters to the new
function to control which DB connection is returned like this (using
the DSN as the parameter):
package Project::DB::Handle;
our %dbh;
use DBI;
sub new {
my $db = shift;
return $dbh{$db} if $dbh{$db};
$dbh{$db} = DBI->connect($db, ...);
}
--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
<http://learn.perl.org/> <http://learn.perl.org/first-response>
--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
<http://learn.perl.org/> <http://learn.perl.org/first-response>