Build ColdFusion Apps that Last with Mach-II

Build ColdFusion Apps that Last with Mach-II

ver heard this story? Developer meets company, company meets developer, they fall in love. Together, they develop a ColdFusion application of great beauty, bound to last forever. But soon developer and company begin to drift apart, feel the need for “more space.” Eventually, they part ways.

A touching story, but the problem is that it doesn’t end there: A new developer enters the picture, but can’t figure out how to modify the application of great beauty. Developer spends lots of time digging through code files, but every time developer tinkers with something, something else breaks. Company falls in love with consultants, out of love with developer, and spends lots of resources doing the same work again.

What Went Wrong?
While we can’t ensure that companies and their software developers will live in harmony forever and ever, we can ensure that the work developers do gets passed from one development team to another team responsibly. An important step in this is application architecture?sets of rules and regulations about how code components within an application interoperate. A clear architecture eases application maintenance.

Application maintenance has long been a problem for the ColdFusion community, as many ColdFusion applications lack clearly defined rules for how code components interoperate. Until recently, ColdFusion lacked object-oriented features, which means strategies to address this lack of rules have been slower in coming to ColdFusion than to other scripting languages. Mach-II is a tool?and a philosophy?to address these issues.

Model-View-Controller Frameworks
The term Model-View-Controller (MVC) has become a mantra of application development in the past few years. Using the MVC design pattern essentially means decoupling the application (or business) logic (the Model) from the user interface (the View) and having the interaction of these two carefully coordinated by a third set of code (the Controller). Mach-II brings the advantages of MVC to ColdFusion for the first time.

The most common problem MVC solves is the tight coupling between application logic and user interfaces. That is, MVC addresses the tendency to introduce data processing code in CF scripts themselves and to hard-code relationships between particular ColdFusion scripts and ColdFusion Components in idiosyncratic?and difficult to understand?ways. Nothing will make a Web application tougher to modify in the future than tight coupling.

The best part of using MVC is that MVC solutions generally come wrapped-up and pre-packaged for us as a set of code?or framework?to which we add the code for our application.

Intro to Mach-II
Mach-II is an object-oriented redesign of the Fusebox 4/MX framework the preceded it. The Fusebox framework is a giant parsing machine that intelligently compiles smaller application scripts (and functionality) into larger scripts (and business logic). Mach-II introduces ColdFusion Components (CFCs) into the Fusebox equation: Mach-II’s object model is built from CFCs, and Mach-II asks application builders to encapsulate their logic in CFCs as well. The results are wonderful: No more spaghetti ColdFusion applications with long scripts everywhere and tightly coupled application and interface code.

How does Mach-II work? Let’s walk through the development of a sample application, a Web-based application to randomly generate band names. To start with, we’ll need to download the Mach-II framework and place it in the ColdFusion wwwroot (see the Resources section, left column). Next, create a directory structure as follows:

/wwwroot/MachII/    <-- MachII framework installation        /bandnamegenerator/config/                          /model/                          /plugin/                          /view/                          /index.cfm

The index.cfm file should contain these lines, which basically just point to the Mach-II framework and set a few global values:

(The downloadable Mach-II sample application framework contains all this for you, but you can use the code distributed with this article as well. See left column.)

Just to get it out of the way, let's write the actual business logic of the application here, which consists of a single CFC, BandNameGenerator, with a single method, generateName(), that returns a CF List of band names based on the type of music the band plays. The first and last lines of the method are as follows:

                            	    			                    		    

I left out a few lines from the middle, but the idea behind this application should be clear: Based on the music type, return a list of randomly generated band names.

So much for an application with a back end. The front end consists of two pages (or "views"), one page consisting of an HTML form where the user selects the music type, and one page where the user gets the results. That's all there is to it.

Here's the HTML from the selection page:

What type of music does your band play?

And here's the HTML from the results page, which iterates through an array of band names stored in the request scope at request.names:

Suggested band names are:

  • #request.names[i]#

Two pages, one method call, all straightforward ColdFusion code.

Enter Mach-II
Now for the Mach-II part. No matter how small your Mach-II application, you will need to use at least four elements of the Mach-II architecture: "events," "event-handlers," "listeners," and "page-views."

A Mach-II "event" is something that happens in the application, and by default that event is announced in the URL using a parameter named event, as in:

index.cfm?event=doSomething

For our application, the big event is selectMusicType, which you can see in the code from the HTML

action attribute above: index.cfm?event=selectMusicType. This event is sent when a user selects a music genre by submitting the HTML form.

Every event has an "event-handler," code that responds to the event and performs the needed action. In this case, our event-handler for selectBandType will want to do two things: 1) get a list of band names by calling generateName() above, and 2) display an interface that shows the results.

Next are Mach-II "listeners," code that is notified by an event-handler when a particular type of event happens. Finally, there are "page-views," which are the ColdFusion scripts that display HTML. To summarize the process: An event occurs, the event-handler looks up the correct listener to respond to the event, and then selects a page-view to display. In my music selection sample, the user selects a music type, the framework calls the generateName() method, and the results are sent to the browser by a ColdFusion script.

The Controller
The epicenter of all this activity is the mach-ii.xml file in the config/ directory. This XML script is used to describe the interaction of the four types of Mach-II elements.

First, we define some properties like the name of our application and the default event:

            

In this application, our default event will be the viewSelectBandForm event. Next, we register the listener:

            	    

This code registers a CFC called bandNameGenerator and tells Mach-II where the CFC is located. The type attribute of the references the physical location of the CFC file, which in this case is in the model/ subdirectory of the application.

You may also notice that the element contains an element. Unless you get into advanced uses of Mach-II, don't worry about the ; just use the one provided above.

Next we register the for the selectMusicType event from our HTML form above.

	            

The event-handler notifies the listener we registered above (bandNameGenerator) by calling its generateName() function. Then the event-handler displays two pages: viewNames and mainLayout. Why two pages? I will explain in a moment.

Next, we register our page-views?ColdFusion scripts which display HTML?all of which are located in the view/ subdirectory of the application:

            	

There are two main interfaces here: ViewSelect.cfm and ViewNames.cfm. The third interface, LayoutMain.cfm, provides a layout shell within which the content from the other two pages will appear. That's why the event-handler for the selectMusicType event references two page-view elements. The key to how this works is the line from the event-handler element:

The contentKey attribute asks Mach-II to take the results of running the ColdFusion script ViewNames.cfm and put it in the variable request.content instead of sending it to the Web browser. So all LayoutMain.cfm has to do is display the contents of that variable:

    Band Name Generator

Band Name Generator

#request.content#

Although an absolutely minimal Mach-II application would not have to use this technique of nesting layouts, it is such a useful and central part of the Mach-II MVC architecture that it is worth using as soon as possible.

And that's it. With all these pieces in place, your Mach-II application is ready to go.

Common Reactions
If you are new to MVC frameworks, it is normal to react with some apprehension to the growing complexity of the mach-ii.xml file. You might find yourself saying: This is a simple program, but it takes all this XML configuration to get it to work. I thought MVC was supposed to simplify my application development!

MVC's big payoff comes not in small applications or in the short term, but in large applications and in the long-term. To see why, think about where the application logic for my sample application would be if it were not in the mach-ii.xml file. Yes, you guessed it: It would be scattered in bits and pieces in the ColdFusion files themselves, via hard coded URLs, and explicit or implicit assumptions about HTTP parameters. What happens when the application grows? That logic grows in kind, and, yes, it is still scattered everywhere. The only way to maintain such an application is with a lot of work.

Explore
There are many other features of Mach-II I don't have space to cover in this article, for example, exception handling, event-mapping, and event-beans. There is also a plug-in API that allows you to extend the framework itself, opening up still more possibilities. The sample application here uses a couple of these to give you a brief taste; the Mach-II site contains many more examples.

The big payoff of using Mach-II, however, will not be found in its bells and whistles, but in its solid delivery of MVC functionality for ColdFusion.

devx-admin

devx-admin

Share the Post:
Clean Energy Adoption

Inside Michigan’s Clean Energy Revolution

Democratic state legislators in Michigan continue to discuss and debate clean energy legislation in the hopes of establishing a comprehensive clean energy strategy for the

Chips Act Revolution

European Chips Act: What is it?

In response to the intensifying worldwide technology competition, Europe has unveiled the long-awaited European Chips Act. This daring legislative proposal aims to fortify Europe’s semiconductor

Revolutionized Low-Code

You Should Use Low-Code Platforms for Apps

As the demand for rapid software development increases, low-code platforms have emerged as a popular choice among developers for their ability to build applications with

Global Layoffs

Tech Layoffs Are Getting Worse Globally

Since the start of 2023, the global technology sector has experienced a significant rise in layoffs, with over 236,000 workers being let go by 1,019

Clean Energy Adoption

Inside Michigan’s Clean Energy Revolution

Democratic state legislators in Michigan continue to discuss and debate clean energy legislation in the hopes of establishing a comprehensive clean energy strategy for the state. A Senate committee meeting

Chips Act Revolution

European Chips Act: What is it?

In response to the intensifying worldwide technology competition, Europe has unveiled the long-awaited European Chips Act. This daring legislative proposal aims to fortify Europe’s semiconductor supply chain and enhance its

Revolutionized Low-Code

You Should Use Low-Code Platforms for Apps

As the demand for rapid software development increases, low-code platforms have emerged as a popular choice among developers for their ability to build applications with minimal coding. These platforms not

Cybersecurity Strategy

Five Powerful Strategies to Bolster Your Cybersecurity

In today’s increasingly digital landscape, businesses of all sizes must prioritize cyber security measures to defend against potential dangers. Cyber security professionals suggest five simple technological strategies to help companies

Global Layoffs

Tech Layoffs Are Getting Worse Globally

Since the start of 2023, the global technology sector has experienced a significant rise in layoffs, with over 236,000 workers being let go by 1,019 tech firms, as per data

Huawei Electric Dazzle

Huawei Dazzles with Electric Vehicles and Wireless Earbuds

During a prominent unveiling event, Huawei, the Chinese telecommunications powerhouse, kept quiet about its enigmatic new 5G phone and alleged cutting-edge chip development. Instead, Huawei astounded the audience by presenting

Cybersecurity Banking Revolution

Digital Banking Needs Cybersecurity

The banking, financial, and insurance (BFSI) sectors are pioneers in digital transformation, using web applications and application programming interfaces (APIs) to provide seamless services to customers around the world. Rising

FinTech Leadership

Terry Clune’s Fintech Empire

Over the past 30 years, Terry Clune has built a remarkable business empire, with CluneTech at the helm. The CEO and Founder has successfully created eight fintech firms, attracting renowned

The Role Of AI Within A Web Design Agency?

In the digital age, the role of Artificial Intelligence (AI) in web design is rapidly evolving, transitioning from a futuristic concept to practical tools used in design, coding, content writing

Generative AI Revolution

Is Generative AI the Next Internet?

The increasing demand for Generative AI models has led to a surge in its adoption across diverse sectors, with healthcare, automotive, and financial services being among the top beneficiaries. These

Microsoft Laptop

The New Surface Laptop Studio 2 Is Nuts

The Surface Laptop Studio 2 is a dynamic and robust all-in-one laptop designed for creators and professionals alike. It features a 14.4″ touchscreen and a cutting-edge design that is over

5G Innovations

GPU-Accelerated 5G in Japan

NTT DOCOMO, a global telecommunications giant, is set to break new ground in the industry as it prepares to launch a GPU-accelerated 5G network in Japan. This innovative approach will

AI Ethics

AI Journalism: Balancing Integrity and Innovation

An op-ed, produced using Microsoft’s Bing Chat AI software, recently appeared in the St. Louis Post-Dispatch, discussing the potential concerns surrounding the employment of artificial intelligence (AI) in journalism. These

Savings Extravaganza

Big Deal Days Extravaganza

The highly awaited Big Deal Days event for October 2023 is nearly here, scheduled for the 10th and 11th. Similar to the previous year, this autumn sale has already created

Cisco Splunk Deal

Cisco Splunk Deal Sparks Tech Acquisition Frenzy

Cisco’s recent massive purchase of Splunk, an AI-powered cybersecurity firm, for $28 billion signals a potential boost in tech deals after a year of subdued mergers and acquisitions in the

Iran Drone Expansion

Iran’s Jet-Propelled Drone Reshapes Power Balance

Iran has recently unveiled a jet-propelled variant of its Shahed series drone, marking a significant advancement in the nation’s drone technology. The new drone is poised to reshape the regional

Solar Geoengineering

Did the Overshoot Commission Shoot Down Geoengineering?

The Overshoot Commission has recently released a comprehensive report that discusses the controversial topic of Solar Geoengineering, also known as Solar Radiation Modification (SRM). The Commission’s primary objective is to

Remote Learning

Revolutionizing Remote Learning for Success

School districts are preparing to reveal a substantial technological upgrade designed to significantly improve remote learning experiences for both educators and students amid the ongoing pandemic. This major investment, which

Revolutionary SABERS Transforming

SABERS Batteries Transforming Industries

Scientists John Connell and Yi Lin from NASA’s Solid-state Architecture Batteries for Enhanced Rechargeability and Safety (SABERS) project are working on experimental solid-state battery packs that could dramatically change the

Build a Website

How Much Does It Cost to Build a Website?

Are you wondering how much it costs to build a website? The approximated cost is based on several factors, including which add-ons and platforms you choose. For example, a self-hosted

Battery Investments

Battery Startups Attract Billion-Dollar Investments

In recent times, battery startups have experienced a significant boost in investments, with three businesses obtaining over $1 billion in funding within the last month. French company Verkor amassed $2.1

Copilot Revolution

Microsoft Copilot: A Suit of AI Features

Microsoft’s latest offering, Microsoft Copilot, aims to revolutionize the way we interact with technology. By integrating various AI capabilities, this all-in-one tool provides users with an improved experience that not

AI Girlfriend Craze

AI Girlfriend Craze Threatens Relationships

The surge in virtual AI girlfriends’ popularity is playing a role in the escalating issue of loneliness among young males, and this could have serious repercussions for America’s future. A

AIOps Innovations

Senser is Changing AIOps

Senser, an AIOps platform based in Tel Aviv, has introduced its groundbreaking AI-powered observability solution to support developers and operations teams in promptly pinpointing the root causes of service disruptions