in reply to How to share DBI connections between objects?

I'm pretty sure that DBI does pool connections, but i can't prove it. Update both adrianh in Re^2: How to share DBI connections between objects? and perrin in Re^2: How to share DBI connections between objects? suggest I made this up.

In your example, I'd have a My->Db method, that returned an already connected $dbh this way all the My:: classes and modules can get a database handle when they want it, and you only have to manage the connecting in once place. Some folks call this a factory

this also means that you can change how the connection is made etc in one place.

@_=qw; ask f00li5h to appear and remain for a moment of pretend better than a lifetime;;s;;@_[map hex,split'',B204316D8C2A4516DE];;y/05/os/&print;

Replies are listed 'Best First'.
Re^2: How to share DBI connections between objects?
by adrianh (Chancellor) on Mar 26, 2007 at 14:34 UTC
    I'm pretty sure that DBI does pool connections, but i can't prove it.

    The connect() method doesn't (unless you're using Apache::DBI). The connect_cached() method does.

    Personally I don't like using this sort of thing since it makes it harder to inject things like test databases in a particular context. I prefer to pass in a configuration object to my application that points to the database, that way I can just build custom config objects for testing.

      I'm not sure I understand. I presume you're objecting to My->Db, right?

      So instead something more like this?

      package My::Underling; our $Db; sub import { my($class, $config_ref )=@_; $Db = DBI->connect( @{$config_ref->{connect_args} } ); } # ... else where in the code import My::Underling \%global_config;
      @_=qw; ask f00li5h to appear and remain for a moment of pretend better than a lifetime;;s;;@_[map hex,split'',B204316D8C2A4516DE];;y/05/os/&print;
        I'm not sure I understand. I presume you're objecting to My->Db, right?

        Kinda. I'm objecting to their being one hard coded $dbh that everything uses. This makes it harder to, for example, swap in a test database, or maybe decide to split a system over multiple databases.

        This isn't really just an issue of database handles, but all "shared" configuration information.

        Instead I pass configuration objects in at object construction time, or use factories like Rose::DB to allow me to switch things around more easily.

Re^2: How to share DBI connections between objects?
by perrin (Chancellor) on Mar 26, 2007 at 15:19 UTC
    Calling it "pooling" might be overstating the case. When you call connect_cached, it will check to see if the current process already has a connection open with those parameters and return it to you if it does. There is no "pool" of connections and no sharing between processes (or threads).