|By Joe Rinehart||
|April 13, 2005 12:00 AM EDT||
I saw a one-man band once, and it was quite a sight. He had a bass drum on his back, operated by a cog attached to one ankle, thumping as he stomped his foot. Shoestrings tied to the neck of his guitar would move drumsticks attached to a snare drum perched atop the bass drum.
Another string attached to his right elbow operated a cymbal clamped to the side of the snare drum. I spotted duct tape in more than one place. It was a little complicated, and changing anything was bound to affect everything else.
Does this sound like an application you may have worked on? I'll admit it: it sure sounds familiar to me.
Now, I've also seen some very good orchestras. The conductor runs the show. She doesn't necessarily know how to play the viola or the sousaphone, but she knows how to use her musicians, and trusts them to do their jobs.
I don't know about you, but I'd much rather be a conductor. My musicians could change how their instruments worked, but as long as they still played in tune, it wouldn't matter to me. More importantly, I can add new instruments without having to learn to play them or figuring out how to tie, clamp, tape, and/or tack weld them into place.
That's a powerful paradigm, and this power is what the Model-View-Controller (MVC) design pattern gives you.
What Is Model-View-Controller?According to James Dempsey's "Model-View-Controller Song," MVC is a way of organizing your code into "functional segments so your brain does not explode." MVC divides your application into three layers, each with a clearly defined task:
The Model contains all of the business logic and data in your application. It is not a stretch to say that your Model literally is your application. Typically, a Model consists entirely of objects or services such as CFCs, Java classes, and / or Web Services. A Model never has any knowledge of Views or Controllers.
A View is what the user sees, and is how the user interacts with your application. The View's job is to allow user input and display the "state of the Model," an Object-Oriented (OO) way of saying "your application's data." Most often, Views are traditional ColdFusion pages (.cfm). Other mediums such as Flash can also act as views. Because your Model isn't aware of the Views, you can interchange views without affecting your overall application.
The Controller is simply "glue" code that passes data back and forth between the View and the Model. The Controller takes data from the user, such as form data, and gives it to the Model for processing. The results are then given back to the View, which is shown to the user.
While some users of MVC may object to passing the data back through the Controller, it's a common way to implement the MVC pattern in a Web environment. In a desktop application, however, the View might be allowed to ask the Model for its state information directly. However, because of the nature of the Web, it's a lot easier to simply "push" the state information into the View through the Controller.
Why Use Model-View-Controller?I'm sure we've all heard talk about separating "business logic" from "presentation logic," and MVC does exactly that. By putting the Controller in between the Model (business logic) and View (presentation), we're insuring that they're not only separate, but highly reusable because they're not specific to a particular implementation. Additional Views can use the same Model without any modification. More importantly, the internal working of the Model can change without affecting the Views. This should sound familiar: we've arrived at the power described earlier when I said I'd rather be a conductor than a one-man band. Let's revisit what I said earlier, but change a few words:
"My components could change how their internals worked, but as long as they kept the same interface, it wouldn't matter to me. More importantly, I can add new components without having to learn how they work, just how to use them."
That's a very powerful statement to make about application design. Model-View-Controller utilizes Object-Oriented Design concepts known as "decoupling" and "separation of concerns" to achieve this power. In a "traditional" ColdFusion application, each page is responsible for a good deal: business logic, data access logic, presentation logic, and data validation. By isolating the business logic in the Model and the presentation logic in the View and having the two communicate through the Controller, we've "decoupled" the business layer from the presentation layer. Each of the three layers has a responsibility, or "concern" that is separate from the others. As long as the boundaries along which the layers communicate, or "interfaces," remain the same each layer can change its internal functionality without affecting other the other two.
Let's Code: An MVC ExampleBuilding an MVC application in ColdFusion isn't very hard. You'll just need a good understanding of ColdFusion Components (CFCs) and an open mind. If you're not up and running with ColdFusion Components, you may want to read Jeffry Houser's article entitled "ColdFusion Components" when you're through with this article (CFDJ vol. 6, issue 11).
First, we need a problem to Model. For a fun example, I've chosen to Model translation of English phrases into Pig Latin. For our first attempt, I'm implementing a very simple version of Pig Latin - for any given word, move all consonants until the first vowel to the end of the word, and then add "ay." For example, "Model-View-Controller" becomes "odelMay iewVay ontrollerCay."
It's easy enough to encapsulate all the logic for this into a CFC. Listing 1 shows the entire model for our application, contained in PigLatinizer.cfc. You'll see that it has a single method ("Translate") that receives a string, and returns a translated string. At this point, we have a working "Model" of our "problem domain" - translating phrases into Pig Latin.
Now, we need a View to interact with our model. Listing 2 shows our basic translator form. It has a form field that collects a phrase to translate, a submit button, and will optionally show results of the latest translation.
Well, that was easy. We have a Model and View. Now we need a Controller to glue the two together. One approach many have taken is to simply add pseudo-Controller code to the top of their View pages, closely mimicking the standard self-posting form architecture ColdFusion developers have used for years. However, this places the Controller code in your View, eliminating any chance of re-use. Instead of doing this, we're going to use a CFC called PigLatinController. The source code for PigLatinController.cfc is shown in Listing 3. Examining the code reveals that it's pretty simple. There's an empty constructor ("Init") and a single method ("Translate"). While our constructor here remains empty, in the real world, this may be a place to insert information, such as datasource names or other configuration data, that the controller will need to pass along to the Model.
Examining the Translate method shows a controller in action. It first creates the needed portions of the model - in this case, simply an instance of PigLatinizer.cfc. It then passes data from the View (form.phrase) to the Translate method of the PigLatinizer. The user is then redirected to the view, with the resulting translation passed as a URL variable.
Now we have a Model, a View, and a Controller. What we're still lacking, however, is a way to have them all "talk." This is a where a framework is needed.
Building a Simple FrameworkWhile there are two popular frameworks available for what we need to do (Fusebox and Mach-II), we're going to build our own mini-framework using about ten lines of code. It's going to be bare-bones, but it should get the job done while also introducing the need for more robust, application-agnostic frameworks.
Listing 4 shows our Pig Latin's Application.cfm file, where lines 3 - 13 represent our framework. First, we see if the application is initialized. If it's not, we create an instance of our Controller, placing it into the application scope. Second, we examine the URL scope to see if a parameter named "method" exists. If it does, we CFInvoke that method of our controller.
Running Our ApplicationWe've now built a complete MVC application for translating phrases to Pig Latin. Let's step through two page requests, initial and form post, to trace how the pieces of MVC work together.
Initially, the user requests Index.cfm. ColdFusion processes the Application.cfm file. Our framework insures that an instance of PigLatinController (the Controller) exists in the application scope, and then looks for URL.Method. Because URL.Method doesn't exist, no action is taken. Index.cfm (the View) then presents the user with the appropriate form.
The user then enters a phrase and clicks the submit button, and our next request cycle begins.
Again, ColdFusion processes the Application.cfm file and insures that our Controller exists. This time, however, URL.Method is defined, and its value is "Translate." Our mini-framework recognizes this, and invokes the "Translate" method of the Controller.
Inside the Controller, the "Translate" method creates an instance of PigLatinizer (our Model). It passes the data from the View (form.phrase) into the Model's "Translate" method, and collects the result. The Controller then CFLocates the user back to Index.cfm, appending the result of the translation to the URL. Index.cfm, the View, shows the "state of the model" (the translated phrase), and dutifully re-displays the translation form.
Modifying Our ApplicationBecause we've placed the Controller between the Model and the View, changes to the Model won't affect the View, and vice versa. Realizing our implementation of Pig Latin isn't complete and that there are additional rules for handling words beginning with vowels, we need to modify our Model. Luckily, there's a freely available Java class that translates English into Pig Latin. We can modify our Model to use this class instead of its own internal logic (Listing 5 shows this modification). Because we're only changing its internals, and not altering its interface, the rest of our application will remain unaffected. By isolating our changes, and decoupling our business logic from our presentation logic, we've given ourselves a both more powerful and safer way to alter or scale our application.
The Need for FrameworksOur bare-bones framework is fine for our Pig-Latin translator, but I wouldn't want to develop an enterprise application with it. On a low level, the method of processing input in the controller then CFLocating would make it hard to return meaningful validation results - the URL string could become huge! On a higher level, what if one method of the Controller needed to call another method? It'd be easy to add the code to do so, but this may begin to fall outside of the "concern" of the controller (passing data between the View and the Model) and may begin to fall into the realm of business logic or application design. Frameworks such as Fusebox and Mach-II help out in this problem. By removing this control of "flow" from the Controller and letting you organize your application using XML, they both allow the Controller to assume its proper role of passing data. Frameworks have a number of other advantages, but that's another article.
SummaryModel-View-Controller is an elegant way to divide your application into logical layers. Each layer has a single job, and does it well. The Model represents your application's business logic. The View presents data from the Model, and accepts user input. The Controller serves to pass data between the View and the Model. Most importantly, the Controller serves to decouple the View from the Model, isolating what changes to bring unprecedented power to your application's design.
Further ReadingThis article provided a high-level introduction to Model-view-controller. Hopefully, it's gotten you interested in using MVC to simplify and enhance your application designs. However, it's glossed over a good deal of Object-Oriented concepts and terminology. There's a lot to learn about the theory of MVC and the various design patterns that are used inside of it (MVC is technically a "compound" pattern, made up of other design patterns).
If you're ready to jump into using MVC for ColdFusion applications, I'd begin by taking a look at the Fusebox (www.fusebox.org), Model-Glue (www.model-glue.com) and Mach-II (www.mach-ii.com) frameworks.".
|Derek 05/04/05 10:45:24 AM EDT|
Where is the sample code for this?
The 3rd International Internet of @ThingsExpo, co-located with the 16th International Cloud Expo - to be held June 9-11, 2015, at the Javits Center in New York City, NY - announces that its Call for Papers is now open. The Internet of Things (IoT) is the biggest idea since the creation of the Worldwide Web more than 20 years ago.
Nov. 27, 2014 02:00 PM EST Reads: 463
An entirely new security model is needed for the Internet of Things, or is it? Can we save some old and tested controls for this new and different environment? In his session at @ThingsExpo, New York's at the Javits Center, Davi Ottenheimer, EMC Senior Director of Trust, reviewed hands-on lessons with IoT devices and reveal a new risk balance you might not expect. Davi Ottenheimer, EMC Senior Director of Trust, has more than nineteen years' experience managing global security operations and assessments, including a decade of leading incident response and digital forensics. He is co-author of t...
Nov. 27, 2014 01:00 PM EST Reads: 1,578
The Internet of Things will greatly expand the opportunities for data collection and new business models driven off of that data. In her session at @ThingsExpo, Esmeralda Swartz, CMO of MetraTech, discussed how for this to be effective you not only need to have infrastructure and operational models capable of utilizing this new phenomenon, but increasingly service providers will need to convince a skeptical public to participate. Get ready to show them the money!
Nov. 27, 2014 11:00 AM EST Reads: 1,183
The Internet of Things will put IT to its ultimate test by creating infinite new opportunities to digitize products and services, generate and analyze new data to improve customer satisfaction, and discover new ways to gain a competitive advantage across nearly every industry. In order to help corporate business units to capitalize on the rapidly evolving IoT opportunities, IT must stand up to a new set of challenges. In his session at @ThingsExpo, Jeff Kaplan, Managing Director of THINKstrategies, will examine why IT must finally fulfill its role in support of its SBUs or face a new round of...
Nov. 27, 2014 10:00 AM EST Reads: 1,142
One of the biggest challenges when developing connected devices is identifying user value and delivering it through successful user experiences. In his session at Internet of @ThingsExpo, Mike Kuniavsky, Principal Scientist, Innovation Services at PARC, described an IoT-specific approach to user experience design that combines approaches from interaction design, industrial design and service design to create experiences that go beyond simple connected gadgets to create lasting, multi-device experiences grounded in people's real needs and desires.
Nov. 27, 2014 08:00 AM EST Reads: 1,130
Enthusiasm for the Internet of Things has reached an all-time high. In 2013 alone, venture capitalists spent more than $1 billion dollars investing in the IoT space. With "smart" appliances and devices, IoT covers wearable smart devices, cloud services to hardware companies. Nest, a Google company, detects temperatures inside homes and automatically adjusts it by tracking its user's habit. These technologies are quickly developing and with it come challenges such as bridging infrastructure gaps, abiding by privacy concerns and making the concept a reality. These challenges can't be addressed w...
Nov. 27, 2014 07:45 AM EST Reads: 1,446
The Domain Name Service (DNS) is one of the most important components in networking infrastructure, enabling users and services to access applications by translating URLs (names) into IP addresses (numbers). Because every icon and URL and all embedded content on a website requires a DNS lookup loading complex sites necessitates hundreds of DNS queries. In addition, as more internet-enabled ‘Things' get connected, people will rely on DNS to name and find their fridges, toasters and toilets. According to a recent IDG Research Services Survey this rate of traffic will only grow. What's driving t...
Nov. 27, 2014 07:00 AM EST Reads: 1,412
Scott Jenson leads a project called The Physical Web within the Chrome team at Google. Project members are working to take the scalability and openness of the web and use it to talk to the exponentially exploding range of smart devices. Nearly every company today working on the IoT comes up with the same basic solution: use my server and you'll be fine. But if we really believe there will be trillions of these devices, that just can't scale. We need a system that is open a scalable and by using the URL as a basic building block, we open this up and get the same resilience that the web enjoys.
Nov. 27, 2014 06:45 AM EST Reads: 1,319
Connected devices and the Internet of Things are getting significant momentum in 2014. In his session at Internet of @ThingsExpo, Jim Hunter, Chief Scientist & Technology Evangelist at Greenwave Systems, examined three key elements that together will drive mass adoption of the IoT before the end of 2015. The first element is the recent advent of robust open source protocols (like AllJoyn and WebRTC) that facilitate M2M communication. The second is broad availability of flexible, cost-effective storage designed to handle the massive surge in back-end data in a world where timely analytics is e...
Nov. 27, 2014 06:45 AM EST Reads: 1,239
We are reaching the end of the beginning with WebRTC, and real systems using this technology have begun to appear. One challenge that faces every WebRTC deployment (in some form or another) is identity management. For example, if you have an existing service – possibly built on a variety of different PaaS/SaaS offerings – and you want to add real-time communications you are faced with a challenge relating to user management, authentication, authorization, and validation. Service providers will want to use their existing identities, but these will have credentials already that are (hopefully) i...
Nov. 27, 2014 04:00 AM EST Reads: 1,140
"Matrix is an ambitious open standard and implementation that's set up to break down the fragmentation problems that exist in IP messaging and VoIP communication," explained John Woolf, Technical Evangelist at Matrix, in this SYS-CON.tv interview at @ThingsExpo, held Nov 4–6, 2014, at the Santa Clara Convention Center in Santa Clara, CA.
Nov. 27, 2014 04:00 AM EST Reads: 1,080
How do APIs and IoT relate? The answer is not as simple as merely adding an API on top of a dumb device, but rather about understanding the architectural patterns for implementing an IoT fabric. There are typically two or three trends: Exposing the device to a management framework Exposing that management framework to a business centric logic Exposing that business layer and data to end users. This last trend is the IoT stack, which involves a new shift in the separation of what stuff happens, where data lives and where the interface lies. For instance, it's a mix of architectural styles ...
Nov. 26, 2014 11:30 PM EST Reads: 1,135
Cultural, regulatory, environmental, political and economic (CREPE) conditions over the past decade are creating cross-industry solution spaces that require processes and technologies from both the Internet of Things (IoT), and Data Management and Analytics (DMA). These solution spaces are evolving into Sensor Analytics Ecosystems (SAE) that represent significant new opportunities for organizations of all types. Public Utilities throughout the world, providing electricity, natural gas and water, are pursuing SmartGrid initiatives that represent one of the more mature examples of SAE. We have s...
Nov. 26, 2014 06:00 PM EST Reads: 1,127
P2P RTC will impact the landscape of communications, shifting from traditional telephony style communications models to OTT (Over-The-Top) cloud assisted & PaaS (Platform as a Service) communication services. The P2P shift will impact many areas of our lives, from mobile communication, human interactive web services, RTC and telephony infrastructure, user federation, security and privacy implications, business costs, and scalability. In his session at @ThingsExpo, Robin Raymond, Chief Architect at Hookflash, will walk through the shifting landscape of traditional telephone and voice services ...
Nov. 26, 2014 02:00 PM EST Reads: 1,552
The Internet of Things is tied together with a thin strand that is known as time. Coincidentally, at the core of nearly all data analytics is a timestamp. When working with time series data there are a few core principles that everyone should consider, especially across datasets where time is the common boundary. In his session at Internet of @ThingsExpo, Jim Scott, Director of Enterprise Strategy & Architecture at MapR Technologies, discussed single-value, geo-spatial, and log time series data. By focusing on enterprise applications and the data center, he will use OpenTSDB as an example t...
Nov. 25, 2014 09:30 PM EST Reads: 1,370
Explosive growth in connected devices. Enormous amounts of data for collection and analysis. Critical use of data for split-second decision making and actionable information. All three are factors in making the Internet of Things a reality. Yet, any one factor would have an IT organization pondering its infrastructure strategy. How should your organization enhance its IT framework to enable an Internet of Things implementation? In his session at Internet of @ThingsExpo, James Kirkland, Chief Architect for the Internet of Things and Intelligent Systems at Red Hat, described how to revolutioniz...
Nov. 24, 2014 07:00 PM EST Reads: 1,678
Bit6 today issued a challenge to the technology community implementing Web Real Time Communication (WebRTC). To leap beyond WebRTC’s significant limitations and fully leverage its underlying value to accelerate innovation, application developers need to consider the entire communications ecosystem.
Nov. 24, 2014 12:00 PM EST Reads: 1,567
The definition of IoT is not new, in fact it’s been around for over a decade. What has changed is the public's awareness that the technology we use on a daily basis has caught up on the vision of an always on, always connected world. If you look into the details of what comprises the IoT, you’ll see that it includes everything from cloud computing, Big Data analytics, “Things,” Web communication, applications, network, storage, etc. It is essentially including everything connected online from hardware to software, or as we like to say, it’s an Internet of many different things. The difference ...
Nov. 24, 2014 11:00 AM EST Reads: 1,702
Cloud Expo 2014 TV commercials will feature @ThingsExpo, which was launched in June, 2014 at New York City's Javits Center as the largest 'Internet of Things' event in the world.
Nov. 24, 2014 09:00 AM EST Reads: 1,725
SYS-CON Events announced today that Windstream, a leading provider of advanced network and cloud communications, has been named “Silver Sponsor” of SYS-CON's 16th International Cloud Expo®, which will take place on June 9–11, 2015, at the Javits Center in New York, NY. Windstream (Nasdaq: WIN), a FORTUNE 500 and S&P 500 company, is a leading provider of advanced network communications, including cloud computing and managed services, to businesses nationwide. The company also offers broadband, phone and digital TV services to consumers primarily in rural areas.
Nov. 23, 2014 07:30 PM EST Reads: 1,879