http://www.perlmonks.org?node_id=1075346


in reply to Best practices passing database handles, cgi objects, etc.

While all of the comments made here are “of course, quite valid,” it’s difficult to make categorical statements about things like this.   What I generally recommend and try to do is to put all “truly-global things” into a package, ordinarily named (say ...) AppGlobals, which contains not only the storage for the global values in question, but “aggressive accessors” for them.   (For instance, a subroutine that is supposed to return a database-handle, finding instead for whatever reason that the handle is undef, will die on the spot.)   If we have to deal with things like “multiple blogs” or what-have-you, the logic in this one place is responsible for dealing with it appropriately.

I specifically prefer not to “pass” such things around, because an error could be introduced by any one (or more) of those “hands” that are supposed to at all times be correctly “holding it” and “passing around the right thing.”   Too many potential points-of-failure for my taste.   So, instead, I define one global place to put things, and I make accessors which are both smart and suspicious.   Clients to this package never access the (private ...) variables directly.   This discipline seems to work out pretty good . . .

Replies are listed 'Best First'.
Re^2: Best practices passing database handles, cgi objects, etc.
by xtpu2 (Acolyte) on Feb 19, 2014 at 02:52 UTC

    I'm not sure I completely understand how your solution differs from that suggested by tobyink (but then, I'm not sure I completely understand his solution... sorry, I don't have much experience with all this!)

    How are the global variables in the AppGlobals module assigned their values? Does the dbh, cgi, session, etc, have to be passed into AppGlobals first? In that case, don't I just simply end up having to pass the AppGlobals object to every one of my subroutines? I suppose this does reduce the argument list from 3 items to just 1 item.

    Or are you suggesting that the CGI object, session and DB handler are actually created inside the AppGlobals package, and then I access them using AppGlobals::get_dbh, AppGlobals::get_cgi, etc? So really it would be like the solution proposed by Anonymous Monk, except moved into a separate package?

    I'm sorry if I'm missing something that should be obvious...