Tobias Kremer wrote:
That's easy under standalone conditions (connect within new, store the dbh in $self->{_dbh} and use that in other methods).
I don't recommend doing that. Better to use DBI->connect_cached in most cases. It will actually check to see if your connection is still good before trying to use it.
Enter mod_perl. I'd like to create the object only ONCE during server startup because it has to do some fairly heavy processing with data from the database which I don't want to be done on every request. The resulting state (some data structures) should then be saved within the object's attributes for later quick and easy retrieval during the request phase. Furthermore this object has methods which execute more database queries (using the handle stored in $self->{_dbh}).
That all sounds fine, except for storing the handle.
Now here's my concern: Because Apache::DBI will not cache the database handle that was created during startup (some mechanisms luckily prevents this), I fear that I might run into trouble having requests using the object generated at server startup with a non-cached handle inside that is shared among all apache children. I know that one should connect in the request phase and let Apache::DBI do the magic, but in this case, where the module is designed to be also used standalone, this is quite tricky IMHO.
You need to separate managing your database connections from caching this data. They are not related, and there's no reason to do both in one class. Either just call connect_cached all the time (it uses Apache::DBI when it finds it loaded), or make your own database connection singleton that decides how to connect in the current environment. Keep your data in the object as you planned.
- Perrin