onMissingMethod Example
CFCs support an onMissingMethod function. By defining an onMissingMethod function in the cfcomponent tag body in the CFC, you can handle calls to methods that are not implemented in the CFC. If an application calls a function that is not defined in the CFC, ColdFusion calls the onMissingMethod function and passes it the requested method's name and arguments.
If you do not define an onMissingMethod function, a call to a method that is not defined in the CFC causes ColdFusion to throw an error that must be handled in the calling code.
The onMissingMethod function is useful for several purposes: To handle errors directly in the component, instead of requiring that each instance of code that calls the component handles them. To create a dynamic proxy, an object that can take arbitrary calls and dynamically determines the correct action.
The onMissingMethod function must have the following format:
<cfargument name="missingMethodName" type="string">
<cfargument name="missingMethodNameArguments" type="struct">
code to handle call to nonexistent method
</cffunction>
The following example shows usage of onMissingMethod.
This is the code for cfc:
<cfargument name="x" required="true">
<cfargument name="y" required="true">
<cfset total = x + y>
<cfreturn total>
</cffunction>
<cffunction name="OnMissingMethod">
<cfoutput><br><br>*****************************************************<br></cfoutput>
<cfoutput>Hello, Welcome to cf-examples.net...<br>
You are trying to call the method "#arguments.missingMethodName#" with parameters:
#arguments.missingmethodarguments.1# and #arguments.missingmethodarguments.2#
<br> This method does not exist.<br><br>
This is from the onMissingMethod.</cfoutput>
<cfoutput><br><br>*****************************************************<br></cfoutput>
</cffunction>
Following below is the cfm code:
<cfset mytestobj = createobject("component", "mytest")>
<!--- call the method sum with arguments --->
<cfset result = mytestobj.sum("5", "2")>
<!--- output the obtained result --->
<cfoutput>The result value is: #result#</cfoutput>
<!--- Try to call a method which does not exist. The control should go to the onMissingMethod in the cfc. --->
<cfset result = mytestobj.multiply("5", "2")>
You can download the source code using the download button.
Here are a few useful links related to onMissingMethod.
http://livedocs.adobe.com/coldfusion/8/htmldocs/help.html?content=Tags_c_10.html
http://www.bennadel.com/blog/868-Learning-ColdFusion-8-OnMissingMethod-Event-Handler.htm
http://www.coldfusionjedi.com/index.cfm/2008/6/13/Ask-a-Jedi-Problem-using-onMissingMethod-inside-a-CFC
http://www.coldfusionjedi.com/index.cfm/2007/8/5/Warning-about-onMissingMethod
