Writing and Invoking a CFC Method - Exercise

Contact Us or call 1-877-932-8228
Writing and Invoking a CFC Method - Exercise

Writing and Invoking a CFC Method

Duration: 15 to 25 minutes.

In this exercise, you will write a new method called ImageRand in the images component.

  1. Open CFCs/Exercises/Images.cfc in your editor.
  2. Write a function called ImageRand that takes two arguments:
    • directory, which is required
    • extensions, which has the default value of "jpg, gif"
  3. Create an aryImages array of the files specified in the directory. (Hint: use the already-defined getFileList method).
  4. Set a variable called picture that gets a random number between 1 and the number of elements in aryImages.
  5. Set the imagepath variable to contain the path to the randomly chosen image.
  6. Return imagepath.
  7. To test your solution, open CFCs/Exercises/RandImage.cfm in your browser, which calls the ImageRand method you just created. You should see a random image from the Images/Runners directory every time you refresh the page.

Solution:

CFCs/Solutions/Images.cfc
<cfcomponent>

	<cffunction name="ImageFlipper" access="public" returntype="string">
		<cfargument name="directory" type="string" required="true">
		<cfargument name="extensions" type="string" default="jpg,gif">
		<cfset aryImages = getFileList(arguments.directory,arguments.extensions)>
		<cfparam name="SESSION.picture" default="0">
		<cfset SESSION.picture = SESSION.picture + 1>

		<cfif SESSION.picture GT ArrayLen(aryImages)>
			<cfset SESSION.picture = 1>
		</cfif>
		<cfset imagepath="#arguments.directory#/#aryImages[SESSION.picture]#">
		<cfreturn imagepath>
	</cffunction>
	
	<cffunction name="ImageRand" access="public" returntype="string">
		<cfargument name="directory" type="string" required="true">
		<cfargument name="extensions" type="string" default="jpg, gif">
		<cfset aryImages = getFileList(ARGUMENTS.directory,ARGUMENTS.extensions)>
		
		<cfset picture = RandRange(1,ArrayLen(aryImages))>
		
		<cfset imagepath = "#ARGUMENTS.directory#/#aryImages[picture]#">
		
		<cfreturn imagepath>
	
	</cffunction>
	
	<cffunction name="getFileList" access="private" returntype="array">
		<cfargument name="directory" type="string" required="true">
		<cfargument name="extensions" type="string" required="true">
		<cfdirectory directory="#ExpandPath(ARGUMENTS.directory)#"
			action="list" name="getFiles">
		<cfset filenames = ArrayNew(1)>
		<cfloop query="getFiles">
			<cfset FileExt = ListLast(name,".")>
			<cfif ListContainsNoCase(ARGUMENTS.extensions,FileExt) AND type EQ "File">
				<cfset ArrayAppend(filenames,name)>
			</cfif>
		</cfloop>
		<cfreturn filenames>
	</cffunction>
	
</cfcomponent>
Next