Change “global” datasource dynamically
-
02-07-2021 - |
Question
I usually set application-wide datasource name in the Application.cfc first rows:
<cfscript>THIS.datasource="mydsn";</cfscript>
What if I need to change it in certain part of my code?
To be specific, I mean:
- if the cgi.server_name equals "www.firsturl.com" => this.datasource = "firstdsn"
- if the cgi.server_name equals "www.secondurl.com" => this.datasource = "seconddsn"
Can I do that for each request?
Solution
OK, my comment on your original post notwithstanding - that the best way to find out these things is just try it and see what happens, the answer is: yes.
Application.cfc is poorly named, because it implies it's kind of application-specific, but in reality the entire thing is instantiated every request. That some of the event handlers only run in given situations (onApplicationStart / onSessionStart etc) is neither here nor there: the whole thing runs every request. So as with any CFC being instantiated, the pseudo-constructor code (where you make your this-scoped variable declarations) is also run every request.
This means that yes you can conditionally set any of those variables based on REQUEST-specific information (request, CGI, URL, FORM etc; but not APPLICATION or SESSION). So your condition based on a CGI variable will work just fine.
But don't take my word for it: try it! Always try these things.
Finally, just to plug myself slightly, I discuss when things run in Application.cfc in some depth on my blog, in this article. Maybe give it a read, and perhaps look at the other articles on Application.cfc whilst you're there.