所以,假设我有这个组件的一个实例:
foo.cfc
<cfcomponent>
<cffunction name="locateMe">
<cfreturn "I don't know where I live!">
</cffunction>
</cfcomponent>
而且,另一个组件 fooParent.cfc:
<cfcomponent>
<cfset this.foo = createObject("component", "foo")>
</cfcomponent>
假设我以几种不同的方式创建“foo”的实例:
<cfset myStruct = {}>
<cfset myStruct.foo = createObject("component", "foo")>
<cfset myFoo = createObject("component", "foo")>
<cfset myFooParent = createObject("component", "fooParent")>
<cfoutput>
#myStruct.foo.locateMe()#<br>
#myFoo.locateMe()#<br>
#myFooParent.foo.locateMe()#<br>
</cfoutput>
正如预期的那样,这输出:
I don't know where I live!
I don't know where I live!
I don't know where I live!
我想知道的是,我可以在 foo.cfc 中做些什么来告诉我一些(任何东西!)关于它被调用的上下文?由于一切最终都存在于(至少)某种范围内,并且所有范围都是一种对象,我的意思是我真的很想从给定的实例化对象中确定包含对象的某种方式。最终,某种构建 foo.cfc 的方式,以便像这样的东西可以作为我的输出,来自我上面的示例片段:
I live within a "class coldfusion.runtime.Struct" instance!
I live within a "class coldfusion.runtime.VariableScope" instance!
I live within a "component cfjunk.fooParent" instance!
其中每个值都可以通过检查传递getMetaData
实际包含对象引用的结果来确定。
更新正如 Micah 在评论中所建议的那样,我已经为此添加了“Java”标签,因为我怀疑他可能是正确的,因为解决方案可能在于使用 Java 进行自省。
更新
与其让这个看起来像是纯粹的学术讨论,让我解释一下为什么我需要这个。
我正在使用带有包含的 CFWheels ORM 来获取对我的数据的引用,如下所示:
var user = model("User").findOne(where="id=123", include="AuthSource", returnAs="object");
这将返回给我一个我可以像这样引用的对象:
user.id // property of the "User" model
user.reset() // method on the "User" model
user.AuthSource.id // property of the "AuthSource" model
user.AuthSource.authenticate(password) // method on the "AuthSource" model
现在,在我的“AuthSource.authenticate”方法中,我想知道我包含在其中的“用户”对象。否则,我最终将不得不像这样调用函数,而不是:
user.AuthSource.authenticate(user, password) // note the redundancy in the use of "user"
我应该能够依赖这样一个事实,即我通过 User 对象调用 AuthSource 模型上的方法,并从该方法中实际读取该对象。