Thursday, March 5, 2009

Remote Component Variable Injection: Now with Method Replacement!

So I woke up this morning and realized you that since you're able to modify variables outside a component, you should be able to modify methods as well. Here's the updated code that proves it.

Application.cfc

<cfcomponent output="false">

<cfset this.name = "moodswing" />

<cffunction name="onApplicationStart">

<cfset application.person = createObject("component","person").init("sad") />
<cfset application.moodswing = createObject("component","moodswing") />

</cffunction>

<cffunction name="onRequestStart">

<cfif StructKeyExists(url,"init")>
<cfset onApplicationStart() />
</cfif>

</cffunction>

</cfcomponent>


person.cfc

<cfcomponent>

<cffunction name="init" returntype="any">
<cfargument name="mood" required="true" type="string" />

<cfset variables.mood = arguments.mood />

<cfreturn this />

</cffunction>

<cffunction name="getMood" returntype="string">

<cfreturn variables.mood />

</cffunction>

</cfcomponent>


moodswing.cfc

<cfcomponent output="false">

<cffunction name="getHappy" returntype="void">

<cfset application.person.changeVariable = changeVariable />

<cfset application.person.changeVariable("mood","happy") />

<cfset StructDelete(application.person,"changeVariable") />

</cffunction>

<cffunction name="getMad" returntype="void">

<cfset application.person.changeFunction = changeFunction />

<cfset application.person.changeFunction("getMood",getMood) />

<cfset StructDelete(application.person,"changeFunction") />

</cffunction>

<cffunction name="changeVariable" returntype="void">
<cfargument name="key" required="true" />
<cfargument name="value" required="true" />

<cfset variables[arguments.key] = arguments.value />

</cffunction>

<cffunction name="changeFunction" returntype="void">
<cfargument name="key" required="true" />
<cfargument name="value" required="true" />

<cfset this[arguments.key] = arguments.value />

</cffunction>

<cffunction name="getMood" returntype="string">

<cfreturn "mad!!!" />

</cffunction>

</cfcomponent>


default.cfm

<cfoutput>
Current mood: #application.person.getMood()# <br />

#application.moodswing.getHappy()#

<br />
After mood swing: #application.person.getMood()# <br />

#application.moodswing.getMad()#

<br />
After another mood swing: #application.person.getMood()# <br />
</cfoutput>


Again, if you run the above code, you should end up with something like this:

Current mood: sad

After mood swing: happy

After another mood swing: mad!!!


And yes, waking up and immediately thinking about this stuff does make me a huge nerd.

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.