2010-02-12 58 views
1

对于我的查找表,这是在应用程序的每个用户相同的那些,我在init方法做一个将数据放入应用范围

Application.objectname = createobject(...).init(datasource) 

,我读表到这个范围像这样:

cfquery name="this.queryname" 
return this 

现在,每当我需要引用查询,可以参考我这样说:

cfselect query="Application.objectname.queryname" ... 

问:那有什么问题吗?

+1

这是好的,只要把这个查询的结果是每个用户/请求相同/随你。如果需要更改,请不要使用应用程序范围。 – 2010-02-12 19:22:37

回答

3

不,这样可以。服务器将整个对象实例保留在内存中,作为应用程序范围的一部分,该范围将包含其所有属性。

作为一种风格问题,我建议将您的查询设置为私有财产(在CFC中的variables范围内)而不是公共财产(在CFC的this范围内)。允许公开对象属性意味着作为黑匣子设计师,您可以与未知的开发人员重写该值。如果这些是你存储的数据库查找表,我猜你打算这些数据是只读的。考虑以下几点:

<cfcomponent hint="Proxy for database lookup tables" output="false"> 
    <cfproperty name="variables.lookupTable1" type="query" hint="[Private] lookupTable1 query object." /> 
    <cfproperty name="variables.lookupTable2" type="query" hint="[Private] lookupTable2 query object." /> 
    <!--- Implicit initialization ---> 
    <cfscript> 
     variables.lookupTable1 = QueryNew(''); 
     variables.lookupTable2 = QueryNew(''); 
    </cfscript> 

    <!--- Active initialization ---> 
    <cffunction name="init" returntype="void" access="public" hint="Initializes the query objects with data." output="false"> 
     <cfargument name="dsn" type="string" required="true" hint="The datasource to use." /> 
     <cfquery name="variables.lookupTable1" datasource="#arguments.dsn#"> 
      SELECT * FROM [TblFoo] 
     </cfquery> 
     <cfquery name="variables.lookupTable2" datasource="#arguments.dsn#"> 
      SELECT * FROM [TblBar] 
     </cfquery> 
    </cffunction> 

    <!--- Data Fetching Methods ---> 
    <cffunction name="getFoo" returntype="query" access="public" hint="Returns the contents of TblFoo." output="false"> 
     <cfreturn variables.lookupTable1 /> 
    </cffunction> 

    <cffunction name="getBar" returntype="query" access="public" hint="Returns the contents of TblFoo." output="false"> 
     <cfreturn variables.lookupTable2 /> 
    </cffunction> 
</cfcomponent> 
+1

:)不要忘记为所有函数添加output =“false”以消除CF生成的额外空白。 – Henry 2010-02-12 20:40:01

+0

我明白了。这两个QueryNew定义的目的是什么?它是一种声明变量的方式,以便代码可以自行记录,或者它是否具有何时使用它的逻辑条件? – 2010-02-12 20:44:03

+1

我猜他们是作为安全卫士出现的,所以如果你忘记调用init(),你的getFoo()和getBar()不会抛出异常。你可以忽略它们。 – Henry 2010-02-12 21:07:17

1

从句法上看,没有。但是,我假设您已经为该cfselect标签添加了“name”属性,因为它是必需的。

+0

是的,我用椭圆表示我故意留下一些东西。 – 2010-02-12 20:38:29

1

如果这是你使用的查询对象的唯一的地方,你可能想缓存cfselect下拉框的输出来代替。 :)

如果你不是在onApplicationStart()onServerStart()设置应用程序范围的变量,那么不要忘记使用<cflock>