ColdFusion

Results 1 - 10 of around 2 in coldfusion

onMissingMethod for dynamic set and get methods

ColdFusion 8 introduces this to deal with calls to methods that don't exist. This can be used for a few things but the most interesting of which it dynamic set and get methods to access an objects' properties.

Here for my reference more than anything and shown in a CFC.

Test.cfc:

<cfcomponent>

  <cfset VARIABLES.property1 = "">
  <cfset VARIABLES.property2 = "">

  <cffunction name="onMissingMethod" output="false">
  
    <cfargument name="missingMethodName" type="string" required="true">
    <cfargument name="missingMethodArguments" type="struct" required="true">
    
    <cfset var action = Left(ARGUMENTS.missingMethodName, 3)>
    <cfset var property = Right(ARGUMENTS.missingMethodName, Len(ARGUMENTS.missingMethodName) - 3)>
  
    <cfif action EQ "get" AND StructKeyExists(VARIABLES, property)>
      <cfreturn VARIABLES[property]>
    <cfelseif action EQ "set" AND StructKeyExists(VARIABLES, property)>
      <cfset VARIABLES[property] = ARGUMENTS.missingMethodArguments[1]>
    <cfelse>
      <cfthrow type="InvalidMethodNameException" message="The method #ARGUMENTS.missingMethodName# was not found in component<br />#GetCurrentTemplatePath()#">
    </cfif>
  
  </cffunction>

  <cffunction name="setProperty2">
    <cfargument name="property2">
    <cfset VARIABLES.property2 = ARGUMENTS.property2>
  </cffunction>

  <cffunction name="getProperty2">
    <cfreturn VARIABLES.property2>
  </cffunction>

</cfcomponent>

onMissingMethod checks for 'set' or 'get' at the start of the method name and assumes the rest is a reference to a property in the CFC. If it can't set or get a property, it throws the same error it would have if onMissingMethod wasn't defined.

test.cfm:

<cfset test = CreateObject("component", "test")>

<cfset test.setProperty1("This is set with the onMissingMethod... method")>
<cfset test.setProperty2("This will be set with the setProperty2 method")>

<cfoutput>
	<p>#test.getProperty1()#</p>
	<p>#test.getProperty2()#</p>
</cfoutput>

The above code shows how you can override the dynamic setters and getters by defining them yourself.

Comments

Nice post, this really helped me out.

James Privett - Wednesday 1 October 2008 at 12:02

Add comment

Name

Comment

Website