Search code examples
coldfusionlucee

coldfusion string to function or dynamic cfc


I am working on a code generation project that I would like to dynamically create structs with functionality. I have found you can define functions for a struct, but I want to dynamically generate the name, return value, and any statements inside of the function. I figured a string would allow me to do this but I can't figure out how to convert a string to a function. Is this possible, if not, is it possible to dynamically generate a CFC?

<cfset j = structnew()>
<cfset j.test = evaluate('function(){ return "test"; }')>
<cfdump var="#j#">
<cfabort>

Solution

  • You can dynamically create a .cfc the same way you can dynamically create a .cfm.

    Step 1 - create the file content as a string variable.

    Step 2 - use cffile to write the file.

    Step 3 - bring the file into your page. With .cfm files this would be a <cfinclude> tag. With .cfc files, maybe a createObject (function)

    Step 4 - use the code in the file.

    Step 5 - delete the file.