ColdFusion Article

Icon or Spacer Icon or Spacer Icon or Spacer
Tom Muck

Tom Muck
DW Team.com
 

Switching from PHP to ColdFusion


If you are a PHP developer looking to learn Macromedia ColdFusion, you will find it is an easy transition. Although the two technologies are very different, a basic understanding of PHP will provide many of the skills required to make the change. The reasons for making such a change will be varied—it may be a project requirement, or you may want to increase your productivity. We'll address both topics in this article, as well as discuss some of the new features that make ColdFusion MX even more attractive for developers.


PHP vs. CFML
PHP is a server platform and a scripting language. The scripting language contains many useful built-in functions that enable your pages to display dynamic content. If you have developed with the PHP scripting language, you'll find that the ColdFusion language (ColdFusion Markup Language, or CFML) is quite a bit different, but also similar in many ways.

First of all, ColdFusion objects (tags) are all inherently active. In ColdFusion, the tag takes care of the creation and the cleanup. When the tag is placed on a page, it is instantiated by the ColdFusion server. The server takes care of the cleanup as well.

This differs from PHP. When developing in PHP, you must create an instance of an object, use the object, and then later destroy the object. For example, when working with a recordset in PHP, you first create the connection and the recordset:

  
<?php
$connMysqlbookstore = mysql_pconnect("tom", "tom",  "mypassword") or 
die(mysql_error());
mysql_select_db("bookstore", $connMysqlbookstore);
$query_rsGetOrders = "SELECT CustomerID, OrderDate  FROM Orders";
$rsGetOrders = mysql_query($query_rsGetOrders, $connMysqlbookstore)  
or die(mysql_error());
$row_rsGetOrders = mysql_fetch_assoc($rsGetOrders);
$totalRows_rsGetOrders = mysql_num_rows($rsGetOrders);
?>

Next, you must use the recordset on a page by manually looping through your recordset:

 
<table>
<?php do {
?>
<tr>
<td><?php echo $row_rsGetOrders['CustomerID']; ?></td>
<td><?php echo $row_rsGetOrders['OrderDate']; ?></td>
</tr>
<?php } while ($row_rsGetOrders = mysql_fetch_assoc($rsGetOrders));
?>
</table>

And finally, if you are done with the recordset, you must free the results and close the connection:

<?php
mysql_free_result($rsGetOrders); 
mysql_close($connMysqlbookstore);
?> 					  

When doing the same thing in ColdFusion, remember that the ColdFusion tags are the equivalent of a server-side object in PHP. A <cfquery> tag is used in place of the recordset in PHP:


<cfquery name= "rsGetOrders" datasource=  "bookstore">
SELECT CustomerID, OrderDate FROM Orders
</cfquery> 
					  

This code creates the recordset. Once it's created, all you have to do is display it. Looping is built into the ColdFusion tags as well, so it's not necessary to manually start or stop the loop. You can simply output the results with a <cfoutput query> tag:

<table>
    <cfoutput query="rsGetOrders">
      <tr> 
         <td>#rsGetOrders.CustomerID#</td>
         <td>#rsGetOrders.OrderDate#</td>
      </tr>
    </cfoutput>
</table>

The ColdFusion code has several advantages that are evident right from the start: it's shorter and more concise. It's also much easier to understand exactly what the code does, even without programming knowledge. Another advantage is that cleanup code isn't required—you don't have to destroy your objects. The server handles those details. Yet another advantage, that may not be apparent from the code, is that you can use this recordset again and again on the same page. You avoid having to reset your pointers as you would in PHP using a mysql_data_seek() or a similar construct.

Another thing you'll notice from the code is that the database MySQL is specified. The PHP code will not work with any other database. You can't simply upgrade your database to MS SQL Server—because the code will not work. You can use a database abstraction layer in PHP to simplify the database communication, but that involves learning another set of rules and more syntax. With ColdFusion, all databases are handled the same way by <cfquery>. The connection to the database is done in the CF Administrator, and the ColdFusion programmer doesn't have to deal with different syntax.

Using less code
Less code = less typing = more time for programming the meat of your program. Now you don't need to spend as much time on the mundane aspects like the object creation, keeping track of your loops, and the closing and releasing of objects. ColdFusion simplifies these tasks across the board.

Take another example, which demonstrates a common web programming task: sending an e-mail. The e-mail functionality of PHP is built-in, as it is in ColdFusion. However, the syntax is not as intuitive and the code required is more verbose. Note that in both the ColdFusion and PHP examples, we assume that the administrator of the application server has set up the mail server properly:

<cfmail to="#form.tofield#"
 from="admin@mywebsite.com" 
 subject="Your order has been placed">
<cfinclude template="message.cfm">
</cfmail>

If you've ever sent an e-mail from PHP, you know what is required. First, the mail server must be set up correctly on the PHP server. Next, you have to know a little bit about what is required in your mail headers. The PHP mail() function only takes four parameters—to, subject, message, and header—but in many cases certain headers have to be set or the mail will not go through. Some servers will reject an email if the FROM field is not included. For that reason, the headers have to be manually concatenated with line feeds. Knowledge of mail headers is necessary. Alternately, you can use a pre-written script that you might find on the web. The same simple e-mail sent from PHP might look like this:

<?php
$to = $_GET ["txt_tofield"]; 
// set the to field from an incoming form field
$subject = "Your order confirmation number is: ";
$subject .= $_SESSION_["order_number"];
$message = join("",file("message.txt"));
$from = "From: Admin <admin@mywebsite.com>";
$replyto = "reply-to: admin@mywebsite.com";
$header = $from; // set the from field in the header
$header .= "\n"; // add a line feed
$header .= $replyto; // add the reply-to header to the header
mail($to, $subject, $message, $header); // send the e-mail
?>

In the example above, notice that the body of the message is included as a separate file (message.txt). The message body could have easily have been hard-coded into the program, but with ColdFusion, using include files can be very beneficial. An include file in ColdFusion is read and interpreted as though it were part of the page, so it is a simple process to add a text file to the body of an e-mail message. In PHP, you have to read the file into an array and then join the array. Newer versions of PHP will include better file handling, however.

In ColdFusion, these include files can be conditional. In other words, you can access different include files based on criteria that you establish, such as a value in a field from the database. For example, inside the message.cfm page, you might have code that looks like this:

<cfswitch expression = #rsGetAllEmails.emailtext#>
     <cfcase value="A05">
          <cfinclude template="orders_5day.cfm">
     </cfcase> 
     <cfcase value="A15">
          <cfinclude template="orders_15day.cfm">
     </cfcase>
     <cfcase value="A30">
          <cfinclude template="orders_30day.cfm">
     </cfcase>
     <cfcase value="A45">
          <cfinclude template="orders_45day.cfm">
     </cfcase>
</cfswitch>

This use of conditional includes can be extremely useful in maintaining your pages. There is no degradation in performance when using include files in ColdFusion, so you can package your logic within them.

Built-in functionality
One thing that will become apparent after you've coded a couple of ColdFusion sites—much of the same functionality that is built into PHP, or offered as additional modules that you can utilize, is also built right into the ColdFusion language using the tag-based syntax. A few of the more powerful ColdFusion tags (some of them new to ColdFusion MX) are:


CFCOMPONENT Creates and defines a component object; encloses functionality that you build in CMFL within cffunction tags and makes it available to any ColdFusion page on your ColdFusion Server or other remote services, such as web services, Macromedia Flash MX, and so forth.  This is a new feature in ColdFusion MX.  Read more about this in the ColdFusion MX Application Developer Center
CFCHART Creates complex charts and graphs in Macromedia Flash, JPEG, or PNG formats on the fly from your database queries (or other types of queries as well).  This is a new feature in ColdFusion MX.  Read more about this in Tim Buntel's Basic Charting and Graphing with ColdFusion MX.
CFXML Creates an XML document. Additionally, the new ColdFusion XML functions enable you to parse and search XML easily.  This is a new feature in ColdFusion MX.  Read more about this in Nate Weiss's Utilizing XML and XSLT in ColdFusion MX PDF format (528k).
CFDUMP Dumps a complete variable, structure, or query to the page in order to debug your CF pages. This tag is especially handy for dumping a complete result set to the page in a nicely formatted table. This is very helpful when testing and debugging.
CFDIRECTORY Provides you with complete access to any directory on your hard drive for listing, creating, deleting, or renaming directories.
CFFILE Provides you with complete access to the files on your server, including the ability to upload, move, rename, copy, delete, read, read binary, write, or append, all from one simple tag.
CFREGISTRY Reads and writes to the Windows registry.
CFEXECUTE Executes a program, batch file, or other executable on the server.
CFPOP Manages and retrieves e-mail messages from a POP e-mail server.

New features in ColdFusion MX
ColdFusion MX is a new release of a die-hard product that has been completely redesigned from the ground up. This version of ColdFusion is Java-based, but works almost entirely like the previous versions of ColdFusion. ColdFusion tags—with very few exceptions—work in exactly the same manner as described in this article. In fact, most applications created in previous versions of ColdFusion will run without modification.

One of the biggest new developments in ColdFusion MX is that you can use JSP tag libraries with your ColdFusion pages. This means that a ColdFusion programmer can take advantage of any existing tag libraries, as well as create new ones. This is in addition to all of the ColdFusion tags and COM objects that are already in a ColdFusion programmer's arsenal.

Another new, big feature in ColdFusion MX is ColdFusion Components (CFCs). CFCs are self-documenting and self-contained. You can use CFCs through any ColdFusion pages on the ColdFusion server.  Other technologies can access your ColdFusion components if you publish them as web services (for instance, a Macromedia Flash application may use a ColdFusion component to run a database query based on a user's request).

Create CFCs with the cfcomponent tag, and save them with a CFC extension.  Include your CFML logic (such as a cfquery tag, conditional code, and so forth) within a cffunction tag inside of the cfcomponent tag inside the CFC file.  Then, any ColdFusion page on your server can call the functions (also called methods) within the CFC.  For full details on how to use CFCs, refer to the other articles in the ColdFusion MX Application Developer Center, and to the ColdFusion MX documentation book, Developing ColdFusion MX Applications

Developing ColdFusion components that produce web services has one major advantage over producing web services in other technologies—you can create a ColdFusion component web service with standard CFML code in a fraction of the time.  Simply add the attribute access="remote" to the cffunction tag to activate the CFC as a web service.  The following is a simple CFC that reads the contents of a directory and returns a list of JPEG files in that directory:

<cfcomponent>
  <cffunction name="getJPGList" returnType="string">
    <cfdirectory name="fileList"
       action="list"
       directory="H:\public_jpegs" 
       filter="*.jpg"> 
   <cfreturn #ValueList(fileList.name)#>
  </cffunction>
</cfcomponent>

Save this file as getFiles.cfc (Note: You'll need to change the directory based on your directory structure). You can use this CFC on your ColdFusion page to get a comma-separated list of all JPEG files in the H:\public_jpegs directory. To invoke the CFC on a ColdFusion page, use this simple code:

<cfinvoke component="getFiles" method="getJPGList"
 ReturnVariable ="theList"/>

After the cfinvoke tag, use the variable, theList, which contains the entire directory of JPEGs. Transform this simple component into a web service.  Doing so makes the information accessible to anyone on the Internet using any capable technology.  Simply add access="remote" to the cffunction tag in the CFC. ColdFusion MX takes care of all the details, including creating the WDSL file for you. You've successfully published a web service that lists the contents of one of your directories. This is a simple example. Yet, compared to that of another language, it illustrates the simplicity and power inherent in ColdFusion code. Read more about using ColdFusion components in the ColdFusion MX Application Developer Center.

XML parsing
Also, ColdFusion MX has XML parsing built into the language as well. A new tag in ColdFusion MX is the <cfxml> tag. Using <cfxml> makes it easy to create an XML document. Also, new ColdFusion functions can take an XML document and turn it into a ColdFusion structure to easily manipulate the contents. If you've ever parsed XML with PHP, you know what can be involved. You need to keep libraries of functions available to aid you in the parsing. With ColdFusion, once again, you can use simple tags. A typical XML construct to describe a book might look like this:

<books>
    <book>
         <title>Dreamweaver MX: The Complete Reference</title>
         <isbn>0072195142</isbn>
         <url>http://www.dwteam.com/tcr</url>
    </book>
</books>

ColdFusion MX allows you to address the XML construct as a structure, using dot notation. Assuming that the preceding XML structure is contained in a string variable named books, the following code pulls apart the structure created by the XML tags and sets variables to hold the data:

<cfset getBook = XMLParse(books)>
<cfset bookTitle = getBook.books.book.title.xmltext>
<cfset bookIsbn = getBook.books.book.isbn.xmltext>
<cfset bookUrl = getBook.books.book.url.xmltext>

Note that the xmltext method will retrieve the text within the XML tags. To display the variables on the page, you can use simple CFOUTPUT tags:

<cfoutput>
Book Title: #bookTitle#<br>
ISBN: #bookIsbn#<br>
URL: <a href="#bookUrl#">#bookUrl#</a>
</cfoutput>

ColdFusion stores XML internally as a structure, so a simple <cfdump> tag can display the contents of the XML structure to your web page while you are debugging:

<cfdump var=#getBook#>

That one tag will show the following display in your browser:

Figure 1: A CFDUMP tag will display the XML structure on your web page

Session Management
Both ColdFusion and PHP have session management, but if you've ever had to build an application that utilized PHP's built-in session management, you know the limitations. PHP uses the file system to handle sessions, which is slow and lacks flexibility. Also, the PHP session files are left behind in the sessiondata directory. There are third-party libraries (like PHPLib) to manage database-based sessions, but PHP itself doesn't have a mechanism to handle sessions inside a cluster. More in general, PHP doesn't have any out of the box clustering capability. ColdFusion was built for scaling.

ColdFusion has a sophisticated session-handling mechanism that works even if the user has cookies turned off. Session state is maintained in server memory using a unique identifier, and this can be passed from page to page if you determine that the user has turned off cookies. This makes for a more user-friendly web experience, allowing information to be maintained easily across pages.


Summary
PHP is certainly a viable technology to build Web applications, but for PHP programmers who wish to make the change to ColdFusion, the transition can be an easy one. You'll find that applications that once took days can be done in hours, and calls to third-party modules can be a thing of the past. CFML is a versatile language that is self-contained, easy-to-learn, and promotes rapid application development.  Also, with the new additions of JSP tag libraries, ColdFusion Components, XML functionality, and web services in ColdFusion MX, ColdFusion is more versatile than ever before.
 

About the author
Tom Muck is co-author of five Dreamweaver-related books including the bestseller, Dreamweaver UltraDev4: The Complete Reference, and its successor Dreamweaver MX, The Complete Reference.  He is an extensibility expert focused on the integration of Macromedia products with ColdFusion and other languages, applications, and technologies.  Tom has been recognized for this expertise as the 2000 recipient of Macromedia's Best UltraDev Extension Award.  He also authors articles and speaks at conferences on this and related subjects.  As Senior Applications Developer for Integram in Northern Virginia, Tom develops back-end applications for expedited, electronic communications. Tom also runs the Basic-UltraDev site with co-author Ray West and is an advisor for MX inSite magazine.