I am using CF11. In addition to the Datasource component, I created a package of four components ( 1 x Bean, 1 x DAO, 1 x Gateway, 1 x Service) that deals with grapes...
The datasource object and the service object have been persisted in Application.cfc as follows:
<cffunctionname="onApplicationStart"output="false">
<!--- Instantiate the Datasource object --->
<cfsetvarobjDatasource = createObject ('component','components.beans.Datasource').init(
DSName='dns', username='abc',
password='pass') />
<!--- Instantiate and persist the Grape service in the application scope --->
<cfsetApplication.GrapeSVC = createObject('component','components.dataAccess.GrapeSVC').init(
datasource = objDatasource) />
</cffunction>
The service object (GrapeSVC.cfc) acts as a façade pattern to the other inner components: a Bean (Grape.cfc), a DAO (GrapeDAO.cfc) and a Gateway (GrapesGW.cfc).
Now, I have below a CFM template that instantiates the above service object (GrapeSVC) to simply call a method - getAllGrapes() from the gateway - that lists all the grapes in the database:
ListGrapes.cfm
<!--- Instantiate the Datasource object --->
<cfsetobjDatasource = createObject ('component','components.beans.Datasource').init(
DSName='dns', username='abc',
password='pass') />
<!--- Instantiate the Grape service object and pass in the datasource object --->
<cfsetobjGrapeSVC = createObject('component','components.dataAccess.GrapeSVC').init(
datasource = objDatasource) />
<!--- Pull out all grapes from the database --->
<cfsetqResults = objGrapeSVC.getAllGrapes() />
<!--- Dump the results --->
<cfdumpvar="#qResults#"label="getAllGrapes results" />
The code above works fine as long as I keep instantiating the datasource object within the above CFM template. If I take it out, the code breaks. This does not make sense to me since I have already persisted the datasource object in Application.cfc above and mostly because the objective is to avoid repeats. My question therefore is:
What is wrong in the above approach and is there a way to NOT re-instantiate the datasource object in every CFM template?