What is the equivalent of static methods in ColdFu

2020-07-03 09:36发布

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?

2条回答
够拽才男人
2楼-- · 2020-07-03 09:44

One way to create statics in ColdFuison is to put the function or variable in the metadata of the object. Its not perfect but like a static you don't have to create an instance of the object to call them and they'll last until the server is restarted so they are quite fast after the first call.

Here's a quick snippet:

component name="Employee"
{
 public Employee function Init(){
  var metadata = getComponentMetaData("Employee"); 

  if(!structKeyExists(metadata,"myStaticVar")){

   lock name="metadata.myStaticVar" timeout="10"{
    metadata.myStaticVar = "Hello Static Variable."; 
   }
  }

  return this;
 }
}

More detail here: http://blog.bittersweetryan.com/2011/02/using-metadata-to-add-static-variables.html.

查看更多
做个烂人
3楼-- · 2020-07-03 10:00

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.

查看更多
登录 后发表回答