In: Categories » Computers and technology » Programming » Invoking a Component Function
If you invoke a component function by using the CFINVOKE tag, ColdFusion creates an instance of that component and calls the function named in the Method attribute. In essence, ColdFusion instantiates an object of the class of that component, but the name of that object is invisible to you. (It’s internally referenced by ColdFusion Server.) If you use CFINVOKE to call three of a component’s functions in a single ColdFusion template, as shown in the code, ColdFusion Server creates three separate instances of that component to give you what you want, and that’s not very efficient.
<cfinvoke component=”Company” method=”GetCompany” returnvariable=”companyRecord1”> <cfinvokeargument name=”CompanyID” value=”8”> </cfinvoke> <cfinvoke component=”Company” method=”GetCompany” returnvariable=”companyRecord2”> <cfinvokeargument name=”CompanyID” value=”9”> </cfinvoke> <cfinvoke component=”Company” method=”GetCompany” returnvariable=”companyRecord3”> <cfinvokeargument name=”CompanyID” value=”10”> </cfinvoke>
The correct way to call a component’s functions multiple times from a single template is to separately instantiate an object with a formal name and then call the functions of that one instance as you need them. The code shows this principle in action. Notice that the component attribute of the CFINVOKE tag references an instance of the component rather than the component itself.
<cfobject name=”myCompany” component=”Company”> <cfinvoke component=”#myCompany#” method=”GetCompany” returnvariable=”companyRecord1”>
<cfinvokeargument name=”CompanyID” value=”8”> </cfinvoke> <cfinvoke component=”#myCompany#” method=”GetCompany” returnvariable=”companyRecord2”> <cfinvokeargument name=”CompanyID” value=”9”> </cfinvoke> <cfinvoke component=”#myCompany#” method=”GetCompany” returnvariable=”companyRecord3”> <cfinvokeargument name=”CompanyID” value=”10”> </cfinvoke>
You create a single instance of the Company component that persists for as long as the current page request lasts; then you simply call the functions of that one instance as many times as you need. After the current page request ends, ColdFusion automatically destroys the instance that you create. (In the following part, you learn how to make your component instances live longer.) Using the CFOBJECT tag isn’t the only way to instantiate an object. The CreateObject() function returns an object as well. The following three lines of code, for example, produce the same results:
<cfobject name=”myCompany” component=”Company”> <cfset myCompany = CreateObject(“Component”, “Company”)> <cfscript>myCompany = CreateObject(“Component”, “Company”);</cfscript>
Similarly, using CFINVOKE isn’t the only way to invoke a component function. After you create an instance of a component, you can call its methods by using simple dot notation. The code, for example, returns the list of companies produced by the ListCompanies function to a variable named listOfCompanies.
<cfscript> myCompany = CreateObject(“Component”, “Company”); listOfCompanies = myCompany.ListCompanies(‘A’); </cfscript> <cfdump var=”#listOfCompanies#”>
In fact, the code is probably the most popular way of working with component functions for ColdFusion developers who are versed in object-oriented languages, as the syntax is very close to the way that both Java and C++ instantiate objects and call their methods. You can directly access component functions via forms and URLs, but the results are basically worthless. Instead of defining a return value to pass from your function to the function call that invokes it, you must push displayable content directly out of the body of the function, as shown in the code.
<cffunction name=”OutputTest” output=”yes”> <cfquery name=”companyRecs” datasource=”#Request.MainDSN#”> SELECT CompanyID, CompanyName, Address, City, State, ZipCode, Comments FROM Company ORDER BY CompanyName </cfquery> <cfoutput query=”companyRecs”> <p><b>#CompanyName#</b>:<br>#Comments#</p> </cfoutput> </cffunction>
This kind of coding is nasty stuff, folks. Don’t do it. The real power of content-producing functions, whether they are local to a template or encapsulated within a component, comes from returning content contained in a complex variable of a specific data type and then merging the content with presentation code. Separating logic from presentation (and, by extension, data from presentation) should be your mantra. If you absolutely must create a function that directly outputs content, remove the ReturnType attribute from the CFFUNCTION tag and add Output=”Yes”. Never have both a return type and direct output in the same function. The Output attribute actually has the following three states:
Output=”Yes” treats the entire function as if it were inside a CFOUTPUT tag pair.
Output=”No” treats the entire function as if it were inside a CFSILENT tag pair.
Eliminating the Output attribute entirely enables explicit CFOUTPUT tags inside the function to leak output to the caller.
We haven’t been explicit about the Output attribute yet because this is a learning article, and we want to eliminate as much extraneous code as possible so that you can focus your concentration on specific topics. In the preceding parts of this article, you learn how to create a named instance of a component, you find out about the basics of instance properties in a component’s This scope, and you learn the differences between class methods and instance methods. Now to put these theories into action! The instance of the component that you create in the code persists only as long as the page request and then ColdFusion Server automatically destroys it. If you want to work with a persistent component past a single page request, you simply must create it in a persistent scope that lives longer than one request, as shown in the code.
<cfscript> Session.myCompany = CreateObject(“Component”, “Company”); listOfCompanies = Session.myCompany.ListCompanies(‘A’); </cfscript> <cfdump var=”#listOfCompanies#”>
Now this instance persists as long as the user’s session does, which means that its properties do, too. This means that you can execute one ColdFusion template that creates an instance of the Company component, go have a cup of coffee, execute a second ColdFusion template that invokes a function of that component, go place a bid on eBay, execute a third ColdFusion template that invokes another function of that component, and so on, until you pause longer than your session timeout permits and the instance is destroyed. This is why we refer to Company as a long-lived persistent component. Components can also be persisted in the Application scope as well. Just remember that all users of your application use the same instance of your component, so locking becomes even more critical and performance bottlenecks potentially become more of a concern if your component manipulates properties in its This scope. We bet that, right now, you’re thinking, “I’m clustering my application, which means that I don’t use Session variables anywhere, so I’m going to persist my component instance by serializing it with WDDX and storing it in the Client scope.” That’s a clever idea, but unfortunately, it doesn’t work. If you serialize a component instance, the properties in the This scope serialize just fine, but you lose all your functions, so on deserialization, all you get back are the properties.
legal notice
Our website is not responsible for the information contained by this article. Web-articles is a free articles resource.
Suggestion: If you need fresh, daily updated content for your website, feel free to use our service. Click here for more information.
Useful tools and features
related articles
In addition to being one of the easiest Web-programming languages, ColdFusion is also one of the most easily extensible languages, because it can interface with many different technologies, as shown in the following list: Java objects, which are standalone packages of code written in the Java language Custom tags written in C++ or Java, which are pieces of code to be used only with ColdFusion, but which are written in either C++ or Java Java Server Page (JSP) tag libraries, which are originally built for use w...
2. First ColdFusion Application
You learn by doing, and then we go back and explain how ColdFusion worked its magic. Before you get started, though, you must learn a few terms, set up the database, and create the Web directory that you’re going to use. These are some terms that you should know: A template is a file with a .cfm extension. ColdFusion executes these templates and produces HTML that is returned to the user’s browser. A page is what appears in your browser. It is rendered from the HTML that ColdFusion Server sends back ...
3. Building the company add action template
In this article, you create the template that puts your form data into the database. Create a file named CompanyAddAction.cfm inside the Ch02 directory, type the code into the file’s editing window, and save the file. <cfquery name=”InsertCompany” datasource=”#Request.MainDSN#”> INSERT INTO Company( CompanyName, Address, City, State, ZipCode, Comments ) VALUES ( ‘#Trim(Form.CompanyName)#’, ‘#Trim(Form.Address)#’, ...
4. Modifying a Company in the Database
The data that CFQUERY requests from the database comes back in a result set, and the Name attribute tells ColdFusion what that result set is to be named. The SQL statement consists of three clauses: SELECT, FROM, and ORDER BY. SELECT tells the database which columns to retrieve from the database; FROM tells the database which table to retrieve those columns from; and ORDER BY tells the database how to sort the results. The result set returned from CFQUERY contains multiple rows of data, and each row has multiple columns. It would ...
5. Building the company edit action template
The code in CompanyEditAction.cfm is like the code in CompanyAddAction.cfm, but the edit action updates rather than inserts. Create a file named CompanyEditAction.cfm inside the Ch02 directory, type the code into the file’s editing window, and save the file. <cfquery name=”UpdateCompany” datasource=”#Request.MainDSN#”> UPDATE Company SET CompanyName = ‘#Trim(Form.CompanyName)#’, Address = ‘#Trim(Form.Address)#’, City = ‘#Trim(Form.City)...
6. Adding a New Employee to the Database
The CFQUERY in CompanyDeleteAction.cfm uses a DELETE statement with two SQL clauses: DELETE and WHERE. DELETE tells the database the table from which to delete a record, and WHERE tells the database which record to delete. You can watch the company delete process in action. Point your Web browser to http://<yourserver>/CFMXBible/Ch02/CompanyGetDeleteForm.cfm and enter a CompanyID. (To get a valid ID, go to the company list and pick a number from the ID column.) Click Submit to see the chosen company’s informatio...
7. Modifying an Employee in the Database
The DateFormat() function around the DateOfBirth column in the codereturns the employee’s birth date reformatted according to a display mask. DateOfBirth normally comes back from the database in the following format: 2002-01-01 00:00:00.0 That format is not very user-friendly. Calling DateFormat() with a mask of “mm/dd/yyyy” returns the date as follows: 01/01/2002 This version is, of course, more natural and easy to read. The same is true for the employee edit process...
8. Removing an Employee From the Database
The user must have the capability to remove employees from the database. The employee delete process is a simple combination of techniques that you have already learned, such as retrieving a record from the database, displaying that record in a template, and so on. The first page in this process is nearly identical to the employee get edit form. Create a file named EmployeeGetDeleteForm.cfm inside the Ch02 directory, type the code into the file’s editing window, and save the file. <html> <head> <ti...
9. Making direct links to the forms
Say that you want to modify or delete a company. Right now, you need to remember the company’s ID, go back to the launch pad, click Company Edit, and enter the company ID, all just to get to the edit form. Wouldn’t you rather click a company in the list and go directly to the edit form? ... <table> <tr> <td><b>ID</b></td> <td><b>Name</b></td> <td><b>Address</b></td> <td><b>City</b></t...
