in reply to Re: Re: Using objects in exported functions
in thread Using objects in exported functions
If you don't want to pass it everywhere, you have at least two options: either set it as a module-wide parameter, or use objects and store it within each instance of the object. The first results in module code that looks like this:
package Exported; # all the usual stuff here... my $dbh; sub set_dbh ( $ ) { ( $dbh ) = @_; } sub do_query ( $ ) { my ( $key ) = @_; return $dbh->selectrow_hashref( ... ) }
Which is called from the main routine like so:
my $dbh = DBI->connect( ... ); set_dbh( $dbh ); my $answer = do_query( $key );
This will work, but it means that this module can only ever access one database at a time (let alone the bad things that would happen in the presence of threads.) My personal preference is to use an object to encapsulate the necessary context:
package MyQuery; sub new { my ( $class, $dbh ) = @_; return bless { dbh => $dbh }, $class; } sub do_query { my ( $self, $key ) = @_; return $self->{dbh}->selectrow_hashref( ... ); }
Which in turn would be called like so:
my $dbh = DBI->connect( ... ); my $query_obj = MyQuery->new( $dbh ); my $answer = $query_obj->do_query( $key );
This allows you to have two MyQuery objects "alive" at once. Which may or may not matter, but generally if you want to tie specific data (in this case, the $dbh) and some operations together, then consider using an object.
p.s. If you just want a shorthand way for functions in package Exported to refer to $main::dbh as though it were in its own namespace, then you might be able to get by with typeglob aliasing:
package Exported; # blah blah blah :) our $dbh; *dbh = \$main::dbh; # now you can refer to just $dbh and it will use the # value in $main::dbh sub do_query ( $ ) { my ( $key ) = @_; return $dbh->selectrow_hashref( ... ); }
The only thing to watch out for here is that $main::dbh has to be a global name (declared with our), not a lexical variable (don't use my).
|
|---|