In C#, I created static methods to help me perform simple operations. For example:
public static class StringHelper
{
public static string Reverse(string input)
{
// reverse string
return reversedInput;
}
}
Then in a controller, I would call it by simply using:
StringHelper.Reverse(input);
Now I'm using ColdFusion with Model Glue, and I'd like to do the same thing. However, it seems like there's no concept of static methods in ColdFusion. If I create a CFC like this:
component StringHelper
{
public string function Reverse(string input)
{
// reverse string
return reversedInput;
}
}
Can I only call this method by creating an instance of StringHelper
in the controller, like this:
component Controller
{
public void function Reverse()
{
var input = event.getValue("input");
var stringHelper = new StringHelper();
var reversedString = stringHelper.Reverse(input);
event.setValue("reversedstring", reversedString);
}
}
Or is there some place where I can put 'static' CFCs that the framework will create an instance of behind the scenes so I can use it as if it was static, kind of like how the helpers folder works?
Nope, you are correct, there is no concept of static methods in ColdFusion. I think most would solve this problem through the use a singleton utilities in the application scope that are create when the application starts. So in your App.cfc in onApplication start you might have:
<cfset application.StringHelper = createObject("component", "path.to.StringHelper") />
Then when you needed to call it from anywhere you would use:
<cfset reversedString = application.StringHelper.reverse(string) />
Yeah, it's not as clean as static methods. Maybe someday we could have something like them. But right now I think this is as close as you will get.