Simon Baynes: Web Development

Using Constructors in CFCs

When creating objects with ColdFusion I prefer to use a constructor method to set my object&'s properties. So say I have a component called Product.cfc in the folder api in the root directory my constructor method would look something like the following

<cffunction name="init" access="public" returntype="api.Product" output="false">
    <cfargument name="nProductID" type="numeric" required="true">
    <cfargument name="sProductName" type="string" required="true">

        // set arguments into variables scope
        variables = duplicate(arguments);

        return this;

Now there is nothing particularly earth shattering about the function above but it does demonstrate some Object Oriented techniques for ColdFusion. The first thing to be aware of is that the returntype is set to dot notation location of the object this is because all 'init' returns is an instance of the CFC, which is demonstrated by the fact that it returns 'this'. So the init function returns an instance of the object with properties set to the values passed in. You can do this like so.

    // create struct to hold arguments
    stArgs = structNew();
    stArgs.nProductID = 5;
    stArgs.sProductName = "Widget";  

    // create instance of object
    oProduct = createObject("component", "api.Product").init(argumentCollection = stArgs);

So now we will have an object called oProduct.

By Simon Baynes