rss
twitter
    Made it to the hotel. Where is everyone?

ColdFusion 10 - Implicit CFC Constructor

Here is another neat new feature of ColdFusion 10 - Implicit CFC constructor. We can now set CFC properties when instantiating the CFC. This can be done by passing in name/value pairs or a structure. For example, let's assume we have the following CFC.

view plain print about
1<cfscript>
2component accessors="true" persistent="true" table="BOOKS" schema="APP" output="false"
3{
4    /* properties */
5    
6    property name="bookID" column="BOOKID" type="numeric" ormtype="int" fieldtype="id";
7    property name="title" column="TITLE" type="string" ormtype="string";
8    property name="description" column="BOOKDESCRIPTION" type="string" ormtype="clob";
9}
10
</cfscript>

In the past we would need to do this:

view plain print about
1<cfscript>
2 book = new Book();
3 book.setTitle( "My Book Title" );
4 book.setDescription( "A really cool book" );
5
</cfscript>

But now, we can simply do this

view plain print about
1<cfscript>
2 book = new Book( title = "My Book Title", description = "A really cool book" );
3
</cfscript>

Or, we can use this syntax.

view plain print about
1<cfscript>
2 book = new Book( {title:"My Book Title", description:"A really cool book"} );
3
</cfscript>

Notice how when creating the structure, we are using ":" rather than "=". NOTE: You can still use "=" if you so desire, but by allowing us to use ":" it is more consistent with other languages, such as JavaScript.

2 comments

(Comment Moderation is enabled. Your comment will not appear until approved.)
Ryan Anklam said...
What I really like about CF10 is that the borrowed heavily from the good parts of other languages. This feature is very Ruby-like.
milan said...
Nice blog.