Search code examples
coldfusiondatasourcecfccoldbox

Best practice for Datasource use in a CFC


I have an application which uses context sensitive datasources. Currently I keep the datasource information stored a such

reqeust.DB.Datasource = "DatasourceName";
request.DB.Username = "DatasourceUsername"
request.DB.Password = "DatasourcePassword"

I then overwrite the variables depending on the context, so each cfquery tag has the attributes datasource="#request.DB.Datesource#" ... etc ...

I want to start moving to more CFC centric frameworks like Coldbox, but I just don't see how this would work.

Do I need to pass in a datasource object into the init statement of the CFC? This seems like it would be a super PITA.


Solution

  • With CF9, you can this.datasource in Application.cfc as the default datasource. Unfortunately, it doesn't seem to have a way to set username/password

    Either

    A.) use an Dependency Injection framework such as ColdSpring (only suitable for singleton Services), Lightwire or Coldbox's own DI solution (Wirebox). and inject the datasource/username/password through the init constructor or setters.

    B.) set <Datasources> in Coldbox.xml.cfm, see: http://wiki.coldbox.org/wiki/ConfigurationFile.cfm

    <!--Datasource Setup, you can then retreive a datasourceBean
       via the getDatasource("name") method: -->
    <Datasources>
      <Datasource alias="MyDSNAlias" 
                      name="real_dsn_name" 
                      dbtype="mysql" 
                      username=""
                      password="" />
    </Datasources>