Method Chaining and Magic Functions

Gain control of your components without having to write more code than really necessary! Chaining methods is a great way to set properties, and Railo does all the work for you

Method Chaining

With the move to applications that use CFC’s a lot, a bean is a great way to store data. The problem is that creating getter and setter functions in code is rather dull and repetitive. We have added the functionality so that you can set accessors="true" to your CFC’s, this then gives you access to magic getter and setter functions.

For example in our ChainDemo.cfc we have:

<cfcomponent accessors="true">
<cfproperty name="firstname" type="string" setter="true"/>
<cfproperty name="lastname" type="string" setter="true"/>
<cfproperty name="age" type="numeric" setter="false"/>
<cffunction name="init">
<cfreturn this>
</cffunction>
</cfcomponent>

Once we have added accessors="true" to our CFC, we can also add properties with the setter="true" attribute. This allows us to now set variables in a single line:

<cfscript>
chainer = new cfcs.ChainDemo();
dump(var=chainer,label="Empty CFC with generated getters and setters");
chainer.setFirstName("Mark").setLastName("Drew");
dump(var=chainer, label="CFC populated with generated setters");
</cfscript>

You can now see that our component has got the setFirstName() function that returns the object itself, and we can then call the setLastName() directly afterwards.

Of course, we can also set the setter=”false” if we don’t want there to be a setter for a specific property.

Magic functions

Railo has had the ability to call methods on a component via the struct notation, that is, given we have the following object:

component {
variables.firstname = "";
variables.lastname = "";
function getFirstName(){
return variables.firstname;
}
function setFirstName(String name){
variables.firstname = name;
}
function getLastName(){
return variables.lastname;
}
function setLastName(String last){
variables.lastname = last;
}
}

Normally you need to access the variables in this object by using the functions themeselves, so calling something like getLastName() or setFirstName().

Railo allows you to do this without needing to explicitly call the function, so you can do it as you would calling a structure. This can be done by setting the magic functions on in the administrator or setting this.triggerDataMember=true in the Application.cfc. Let’s look at an example of calling the CFC above:

<cfscript>
myUser = new cfcs.UserSimple();
dump(var=myUser, label="Freshly initialised User");
//call the magic functions
myUser.firstName = "Elvis";
myUser.lastName = "Prestley";
dump(var=myUser, label="Freshly populated User");
dump(var=myUser.getLastName(), label="Make sure we have set the surname in the above statement");
</cfscript>