Global mgo.Database object

40 views
Skip to first unread message

Ekliv

unread,
Jun 24, 2011, 12:02:48 PM6/24/11
to mgo-...@googlegroups.com
Hey everyone,

I want to write a little web application. I got several views which all need access to the database. But of course I don't want to start a new session in all of them and besides it would be useful to abstract things in models. So if I don't want to pass a database object to every view function (which wouldn't be possible anyway as my views are called by an independant router) I have to use a global variable for my database object.

If I'm not totally wrong this means I have to open a session in my apps init() in order to catch errors. But at the end of my main() the session must be closed again. So I have to store my session in a global variable, too. This somehow seems like an ugly mess and as soon as I want more databases or sessions to be available in all my views it starts becoming error-prone.
Furthermore global variables are the pure evilness anyway (that's what people use to say from time to time).

So has anyone an idea how to get out of this misery. (Sorry if my problem is not 100% mgo-related.)

Gustavo Niemeyer

unread,
Jun 24, 2011, 12:34:43 PM6/24/11
to mgo-...@googlegroups.com
> Furthermore global variables are the pure evilness anyway (that's what
> people use to say from time to time).

I know it from experience, actually, so I can't really provide you
good advice besides "don't do it". Your views are supposed to have
access to whatever information they need to produce the view output.
This will be good for testing, maintainability, extension, etc.

--
Gustavo Niemeyer
http://niemeyer.net
http://niemeyer.net/blog
http://niemeyer.net/twitter

Reply all
Reply to author
Forward
0 new messages