Introducing CFCs


Before you publish and use Web services using ColdFusion MX, you need to create reusable and server-based components called CFCs, which allow you to create and use the middleware components in ColdFusion applications. CFCs enable you to encapsulate the function of an application and provide an interface to client computers, such as Web pages, Flash movies, and Web services. To access the function, you need to invoke the method of the component. A CFC is a self-documenting and self-contained bundle of methods or functions that you can invoke both locally and remotely on a ColdFusion MX server.

Some of the advantages of using CFCs in ColdFusion MX are as follows:

  • Data abstraction. The data and the actual storage program are completely hidden from the ColdFusion MX application.

  • Improved reuse. Many parts of ColdFusion MX applications allow you to control the existing code and logic quickly and easily.

  • Easy modification. You can make changes in the database schemas without changing a lot of code in ColdFusion MX.

  • Code separation. It's possible to separate the Web content from the code in ColdFusion MX.

CFCs are similar to custom tags, used in the previous versions of ColdFusion, that enable you to reuse the objects anywhere you need them. You only need to make changes to a single component to add, remove, or modify the component functions. Although custom tags are similar to CFCs, these aren't designed for the n-tier application development. These tags were designed to encapsulate the functions of the CFML applications. Table 17.1 lists some of the major differences between custom tags and CFCs.

Table 17.1: Differences Between Custom Tags and CFCs

Custom Tags

CFCs

Custom tags have a single entry point.

CFCs have multiple entry points. This helps to create a single component that's used to perform many related actions.

Custom tags don't have a formalized parameter passing and validation mechanism.

CFCs can validate the passed data and enforce data types.

Custom tags cannot persist themselves.

CFCs are objects that can persist themselves.

Custom tags contain code only.

CFCs contain both the code and data.

You must access the custom tags locally and by using ColdFusion.

CFCs are designed to be accessed in the form of Web services.

Using CFCs in ColdFusion MX

As a developer, you can create and then share your CFCs with other developers. Your CFCs can serve as building blocks for design pattern methodologies. You need to establish design specifications that represent the team's accumulated knowledge and establish the guidelines for application development. These design patterns enable you to streamline software production, manage the application development process, and maintain the lifecycle of ColdFusion MX applications. You need to take the following precautions while using CFCs to create reusable code:

  • CFCs are designed to access all variables in all scopes. However, this should be avoided because CFCs will become transparent to all those applications using them.

  • CFCs should not access session variables until they're set themselves.

  • CFCs should not access CGI variables.

Creating CFCs in ColdFusion MX Applications

As you store ColdFusion application pages, you also need to store CFCs in a domain that is accessible by your Web server and ColdFusion MX. You need to save a component in ColdFusion MX with an extension name of CFC, such as componentname.cfc. You can save CFCs in Web root directories, which are accessible from ColdFusion mappings and the subdirectories of the custom tags roots.

You can use the <cfcomponent> and <cffunction> tags to create CFCs. The <cfcomponent> tag provides an envelope that describes a function built in CFML and encloses it in the <cffunction> tag. You need to use the following syntax for the <cfcomponent> tag:

 <cfcomponent extends="anotherComponent"> 

Here, extends is the attribute of the string data type. This attribute is an optional parameter. This tag is optional in CFCs.

Use the following syntax for the <cffunction> tag:

 <cffunction name="methodName" returnType="datatype"              roles="securityRoles" access="methodAccess" output="Yes/No"> 

  • name. Indicates the name of the component method

  • returnType. Indicates the datatype validation for returned values

  • roles. Assigns the component method to ColdFusion security roles

  • access. Restricts the access of the component method by the client type

  • output. Suppresses the component method output

Building CFCs in ColdFusion MX

The CFC method definition must exist between the opening and closing tags of <cffunction>. Use the <cfinclude> tag to call the component file that contains the component method code. In this section, you'll create a component called Login-Service.cfc, with LoginService as the component name and Login as the function name. The first step is to create a LoginService.cfc file in the Web root directory of the Web server. The following code shows you how to create a CFC:

 <cfcomponent name="loginservice"               displayName="Checks the Logins from the DataBase">     <cffunction name="login" access="remote" returnType="string">         <cfquery name="login" datasource="webservice">           select * from users           where UserName like '#uname#' and password like '#pass#'         </cfquery>         <cfoutput query="loginq">           <cfset login="Success">         </cfoutput>         <cfif #loginq.RecordCount# eq 0>           <cfset login="Fail">         </cfif>         <cfreturn #login#>     </cffunction> </cfcomponent> 

After creating the component and saving it in the Web root directory, you need to allow communication between the component and the ColdFusion application. To do this, you need to invoke the method of the LoginService component in the ColdFusion application. The following section describes the use of the <cfinvoke> tag to invoke the component method.

Communicating with Component Methods

ColdFusion MX applications require data to be passed back and forth across many pages. The preceding example includes multiple ColdFusion pages to collect the data from the user and access the database. Here's how to communicate with components:

  1. Invoke a component method by using the <cfinvoke> tag in ColdFusion pages and components.

  2. Pass a parameter to the component method. Define a parameter when you define the component method. Choose a technique to pass the parameter, and then access the data passed in the parameter.

  3. Return a value from the component method. Use the <cfreturn> tag in the component method definition to specify a variable to return to the client.

Invoking a Component Method

The client application includes Web pages, ColdFusion pages, Flash movies, and Web services. The process of invocation depends upon the type of client that invokes a component method. You can use either the <cfinvoke> tag or the <cfscript> tag to invoke the component method. In addition, you can call the component method in other ways, such as using a URL, FORM Post method, or Flash Remoting Web service.

The next section discusses the common methods of invoking a CFC method.

Using the <cfinvoke> Tag

You can place several <cfinvoke> tags in a ColdFusion page in order to invoke multiple component methods. The following is the syntax for the <cfinvoke> tag:

 <cfinvoke component="componentName" method="methodName"            returnVariable="VariableName" argumentCollection="argumentStruct"> 

This syntax contains the following attributes:

  • Component. Defines the name of the component.

  • Method. Defines the name of the component method.

  • ReturnVariable. Creates a variable by the name entered and assigns the results of the component method to that variable.

  • ArgumentCollection. Passes the structure to the component method as a parameter.

The following is the code snippet used to invoke a method of the LoginService component.

 <cfinvoke component="loginservice" method="login" returnVariable="loginans"> 

Using the <cfscript> Tag

This tag is easier to use. To invoke a component method with the <cfscript> tag, use the createObject function. This helps you place an instance of CFC in a variable. From that variable, you can call functions and methods using the dot notation. The following code snippet shows you how to invoke a component method using the <cfscript> tag:

 <cfscript>     objAdministrator=createObject ("component", "Admin");     bName=objAdministrator.getName (uname, password); </cfscript> 

The preceding code is used to call the getName function. It creates a component object called objAdministrator by setting the objAdministrator variable to the createObject function of ColdFusion MX. The createObject function takes two arguments. The first argument specifies that a component object is to be created, and the second one names the component. The component file will also be named Admin.cfc.

The code then creates and initializes a local variable named bName. Using the dot notation such as objectName.functionName (arguments), the code executes the function with the uname and password arguments.

Using Other Ways to Invoke CFC Methods

Other ways to invoke CFC methods include using the <cfobject> or <Form> tag and using the Flash Remoting component.

Apart from using the <cfinvoke> and <cfscript> tags, you can also use the <cfobject> tag to invoke CFCs. This enables you to separate the installation of the component from the invocation of the component method. To do this, you first need to use the <cfobject> tag to instantiate the component and assign it to a variable. The following code snippet allows you to instantiate a component:

 <cfobject name="TexasTimeComp" component="TexasTime"> 

To invoke a component method, use the <cfinvoke> tag. Its name attribute enables you to reference the variable name in the name attribute of the <cfobject> tag. The following code snippet enables you to invoke a component method:

 <cfobject name="TexasTimeComp" component="TexasTime"> <cfinvoke component="# TexasTimeComp#" method="getTime"> 

You can use a URL to invoke a component method. To do this, you need to append the method name to the URL in the standard URL query-string, named-value syntax. You can also invoke one component method for each request of the URL. The following code snippet shows you how to invoke a component from the URL:

http://Texas:80/EmployeeService.cfc?method=Login

After invoking a component method, you need to pass the arguments into the component method in ColdFusion applications.

Passing Parameters to Component Methods

You need to pass parameters to the created component method to perform the conditional processing in CFCs based on the data sent from the client application. The parameters consist of the username and password information, session state data, and keywords for queries in a database. To pass the parameters to components in ColdFusion MX:

  • Define the parameter in the component method definition.

  • Select the parameter-passing technique.

Defining the Parameter for the Component Method

To define the parameter for the component method, use the <cfargument> tag. You can use the structure or the array like notations, along with the argument variable, to access the parameter values. The following syntax is used for the <cfargument> tag:

 <cfargument name="parameterName" type="datatype"              required="true/false" default="defaultValue"> 

  • Name. Defines the name of the parameter.

  • Type. Defines all the datatypes used for the component in ColdFusion MX.

  • Required. Specifies whether the parameter is required in order to execute the component method.

Selecting the Parameter-Passing Technique

Similar to the CFC methods, you can pass the parameters in various ways, including the <cfinvoke> tag, the <cfinvokeargument> tag, a URL, a form, the <cfscript> tag, or Flash Remoting.

For instance, to pass a parameter to a getName method using the <cfinvoke> tag, you use the following syntax:

 <cfinvoke component="MyComponent" method="getName" FirstName="session.uname"> 

In this example, the FirstName attribute is used to pass the value of the session variable to the component method.

To pass a parameter using the <cfinvokeargument> tag, you use the following syntax:

 <cfinvokeargument name="parameterName" value="anyValue"> 

  • Name. Defines the name of the parameter. It uses the datatype as the string.

  • Value. Defines the value of the parameter. It can take all datatypes.

Both attributes of the <cfinvokeargument> tag are required attributes.

In the preceding sections, you learned how to create a component called LoginService and invoke a method of that component called Login. Now, you'll learn how to pass arguments using the <cfinvokeargument> tag into the method of the LoginService component in a LoginCheck.cfm file. The following code snippet enables you to pass the argument into the component method:

 <cfinvokeargument name="UserName" value="#Form.uname#"> <cfinvokeargument name="Password" value="#Form.Pass#"> 

To pass a parameter using a URL similar to invoking a method, you need to append a parameter to the URL in the standard URL query-string, name-value pair syntax. For example, to pass Albert as the value to the FirstName parameter in the Employees host name, you can use the following syntax:

http://Employees/empComp.cfc?method=getName&FirstName=Albert

You can also use multiple parameters within a URL. To do this, use the ampersand (&) character to delimit the name-value pairs. In the preceding example, use the following syntax to add the values Albert and Development as the first name and department:

http://Employees/empComp.cfc?method=getName&FirstName=Albert&Dept=Development

You can also pass a parameter using an HTML or ColdFusion form. To do this, you need to match the names of the client input controls with the names of the parameter definitions in the component. The following code illustrates how to pass a value to the parameter using the <Form> tag:

 <form action="empComp.cfc " method="post">     <p>Enter employee's First Name:</p>     <input type="Text" name="firstName">     <input type="Hidden" name="method" value="getName">     <input type="Submit" title="Submit"><br> </form> 

In the preceding example, the <Form> tag and the action attribute enable you to point to the empComp component. You can use the <input> tag to invoke the component method. When you open the empComp.cfc component file, the access attribute enables the clients, such as Web browsers and Flash applications, to access the component methods.

Finally, open Internet Explorer and enter the following URL:

/">http://<computername>/<component.cfm>

You can also pass the parameters using the <cfscript> tag. The following example allows you to invoke the getName component method in three different ways and then pass parameters in each invocation:

 <cfscript>     empComp = createObject("component", "Employees");     empComp.getName(FName="Walter" LName="Dick");     tempStruct = structNew();     tempStruct.FName = "Walter"     tempStruct.LName = "Dick"     empComp.getName(argumentsCollention = tempStruct);     empComp.getName("Walter", "Dick"); </cfscript> 

Returning Values from the Method

After passing a parameter to a component method, use the <cfreturn> tag. Unlike the return argument of the cfscript statement, the <cfreturn> tag can accept only one variable. To return more than one value at a time, you need to occupy the structure with named-value pairs and then return the structure using the <cfreturn> tag. You can access the result values that are returned to the client using the variable scope specified as the value of the returnVariable attribute of the <cfinvoke> tag. You need to use the <cfreturn> tag in the component method definition. You can pass the values of all data types, such as string, integer, arrays, and structures.

The following code enables you to return a value from a query that acts as a variable, named Customer, from TGKEmp, an ODBC data source having FirstName and LastName as its values:

 <cfcomponent name="EmpQuery">     <cffunction name="getName">        <cfquery name="Customer" datasource="TGKEmp" dbtype="ODBC">          SELECT LASTNAME, FIRSTNAME          FROM Employees        </cfquery>        <cfreturn Customer>     </cffunction> </cfcomponent> 

Save the file as EmpQuery.cfc in a virtual directory.

To invoke the getName method from the EmpQuery component, use the <cfinvoke> tag. The following code snippet enables you to invoke a component and then display the value in the Web browser:

 <cfinvoke component="EmpQuery" method="getName" returnVariable="result"> <cfdump newvar=#result#> 

In this example, the returnVariable attribute of the <cfinvoke> tag allows you to specify the scope name variable that holds the component method results. Use the <cfdump> tag to display the contents of the result variable. Save the file as EmpFirst.cfm, and enter the following URL in the Web browser to display the ColdFusion application page:

http://localhost/EmpFirst.cfm

Using Advanced Features of CFCs

Using the advanced features of CFCs, you can simplify application development and deployment. Some of the advanced features enable you to

  • Build secure CFCs.

  • Use component packages to avoid conflicts in naming conventions with the components.

  • Import the methods and attributes of other components through inheritance using the extends attribute of the <cfcomponent> tag.

  • Use the component metadata to describe the functions of the component using the CFML programming.

Securing Component Methods

Security is a major concern before users on the Internet can access component methods. CFCs provide various security features to prevent unauthorized users from accessing component methods.

  • Authenticating the Web server. Most of the Web servers allow protection of directories using basic authentication. When a client computer tries to access one of the resources under a protected directory that isn't properly authenticated, the server cancels the authentication of the CFC.

  • Providing role-based security. You can restrict access to CFCs using role-based security. When a component method is restricted to one or more roles using the roles attribute of the <cffunction> tag, users need to be in that role. For instance, if a user called Admin has access to the AddEmployee component function, no other user can access the function. The following code snippet illustrates the use of the roles attribute:

     <cffunction name="AddEmployee" roles="Admin"> </cffunction> 

  • Securing the applications programmatically. You can also restrict the access to components using CFML constructs as ColdFusion pages. For example, you can use the IsUserInRole function to determine whether a user is authenticated in a particular security role.

Using Component Packages

A component doesn't need to be located in the same directory as a ColdFusion page, a Web page, or a Flash movie. CFCs can reside in any folder under a Web root directory on the Web server. The components that are stored in the same directory are considered members of the component package. This prevents any naming conflicts and facilitates easy deployment of a CFC. You can invoke a packaged component method using the <cfinvoke> tag.

Every CFC needs to have a descriptive name, especially if the components are installed as a part of a packaged application. Similar to other programming languages, such as Java, you can reserve the order of the domain name and continue with the application name. This is shown in the following example:

 web.Texas.catalog.services.sww 

When a component is referred to using a fully qualified name, ColdFusion searches in the following order for the ColdFusion component:

  1. Attempts to resolve the physical path from the URL request, such as /web/Texas/catalog/services/sww.cfc, to the component file that is located under a Web root directory.

  2. Attempts to resolve the physical path in the custom tag root, such as {customTagRoot}/web/Texas/catalog/services/sww.cfc.

Inheriting CFCs

Component inheritance allows you to import methods and properties from one CFC to another. In this way, the inherited components share any method or properties of the respective parent CFC components. When you use component inheritance in ColdFusion MX, the inheritance should define a relationship between CFCs.

For example, if the Employee.cfc component inherits the methods of the Admin.cfc component, and in turn Admin.cfc inherits the methods of Texas.cfc, then Employee.cfc is Admin.cfc and Admin.cfc is Texas.cfc. In other words, Employee.cfc is Texas.cfc.

Using the Component Metadata

When you access a CFC directly using the Web browser without specifying component methods, the following sequence of events occurs:

  1. The request to the component is directed to CFCExplorer.cfc, which is located in the \CFIDE\componentutils directory under the Web root directory on the Web server.

  2. The CFCExplorer component then prompts you to enter a ColdFusion RDS password. You need to provide this password while installing ColdFusion MX. You should keep the same password for the ColdFusion Administrator and ColdFusion RDS.

  3. CFCExplorer then renders an HTML description of the component. For example, when you access the Employee component directly from the Web browser, it displays the screen, as shown in Figure 17.1.

    click to expand
    Figure 17.1: HTML description of the Employee component.

The screen in Figure 17.1 displays the methods used in the component that you build in ColdFusion MX. You can also use the cfcToMCDL and cfcToHTML component methods of utils.cfc, located inside the \CFIDE\componentutils directory under the Web root directory on the Web server.

To browse the components developed by you and the system components, you can use the Component browser with componentdoc.cfm, located inside the \CFIDE\componentutils\ directory under the Web root directory on the Web server.




Macromedia ColdFusion MX. Professional Projects
ColdFusion MX Professional Projects
ISBN: 1592000126
EAN: 2147483647
Year: 2002
Pages: 200

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net