Quickstart 2: Modeling our Application

The "Model" for our application will consist of a single CFC that translates a phrase into, well, something else.  In this case, we'll start with pig latin.  To create a CFC-based Model for our application, do the following:

 

1.  Create a file in /translator/model called PigLatinTranslator.cfc

2.  Open the file, and paste in the following code.  You'll see that it's a simple CFC with a constructor function named "init" that receives what letters are considered vowels.  It only has one other function, "translate," which changes a phrase into Pig Latin.

 

<cfcomponent name="PigLatinTranslator" output="false">

 

<cffunction name="init" returntype="any" access="public" output="false">

<cfargument name="vowels" type="string" required="true" />

 

<cfset variables.vowels = arguments.vowels />

 

<cfreturn this />

</cffunction>

 

<cffunction name="translate" returntype="string" access="public" output="false">

<cfargument name="phrase" />

 

<cfset var firstVowel = reFindNoCase("[#variables.vowels#]", arguments.phrase) - 1/>

<cfset var result = trim(arguments.phrase) />

 

<!--- We started with a consonant --->

<cfif len(result) and firstVowel gt 0>

<cfset result = right(arguments.phrase, len(arguments.phrase) - firstVowel) & left(arguments.phrase, firstVowel) & "ay" />

<!--- We started with a vowel --->

<cfelseif len(result)>

<cfset result = result & "ay" />

</cfif>

 

<cfreturn result />

</cffunction>

 

</cfcomponent>

 

 

 

And that's it.  Our entire Model.  It doesn't know anything about a user interface, or form variables, or session, or any of that stuff, so it's very, very reusable.