|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?
In his session at @ThingsExpo, Tony Shan, Chief Architect at CTS, will explore the synergy of Big Data and IoT. First he will take a closer look at the Internet of Things and Big Data individually, in terms of what, which, why, where, when, who, how and how much. Then he will explore the relationship between IoT and Big Data. Specifically, he will drill down to how the 4Vs aspects intersect with IoT: Volume, Variety, Velocity and Value. In turn, Tony will analyze how the key components of IoT influence Big Data: Device, Connectivity, Context, and Intelligence. He will dive deep to the matrix...
Oct. 6, 2015 06:00 AM EDT Reads: 246
Scott Guthrie's keynote presentation "Journey to the intelligent cloud" is a must view video. This is from AzureCon 2015, September 29, 2015 I have reproduced some screen shots in case you are unable to view this long video for one reason or another. One of the highlights is 3 datacenters coming on line in India.
Oct. 6, 2015 05:45 AM EDT Reads: 155
The broad selection of hardware, the rapid evolution of operating systems and the time-to-market for mobile apps has been so rapid that new challenges for developers and engineers arise every day. Security, testing, hosting, and other metrics have to be considered through the process. In his session at Big Data Expo, Walter Maguire, Chief Field Technologist, HP Big Data Group, at Hewlett-Packard, will discuss the challenges faced by developers and a composite Big Data applications builder, focusing on how to help solve the problems that developers are continuously battling.
Oct. 6, 2015 04:00 AM EDT Reads: 407
When it comes to IoT in the enterprise, namely the commercial building and hospitality markets, a benefit not getting the attention it deserves is energy efficiency, and IoT’s direct impact on a cleaner, greener environment when installed in smart buildings. Until now clean technology was offered piecemeal and led with point solutions that require significant systems integration to orchestrate and deploy. There didn't exist a 'top down' approach that can manage and monitor the way a Smart Building actually breathes - immediately flagging overheating in a closet or over cooling in unoccupied ho...
Oct. 5, 2015 11:45 PM EDT Reads: 200
SYS-CON Events announced today that IBM Cloud Data Services has been named “Bronze Sponsor” of SYS-CON's 17th Cloud Expo, which will take place on November 3–5, 2015, at the Santa Clara Convention Center in Santa Clara, CA. IBM Cloud Data Services offers a portfolio of integrated, best-of-breed cloud data services for developers focused on mobile computing and analytics use cases.
Oct. 5, 2015 11:00 PM EDT Reads: 608
The enterprise is being consumerized, and the consumer is being enterprised. Moore's Law does not matter anymore, the future belongs to business virtualization powered by invisible service architecture, powered by hyperscale and hyperconvergence, and facilitated by vertical streaming and horizontal scaling and consolidation. Both buyers and sellers want instant results, and from paperwork to paperless to mindless is the ultimate goal for any seamless transaction. The sweetest sweet spot in innovation is automation. The most painful pain point for any business is the mismatch between supplies a...
Oct. 5, 2015 03:30 PM EDT Reads: 126
Mobile messaging has been a popular communication channel for more than 20 years. Finnish engineer Matti Makkonen invented the idea for SMS (Short Message Service) in 1984, making his vision a reality on December 3, 1992 by sending the first message ("Happy Christmas") from a PC to a cell phone. Since then, the technology has evolved immensely, from both a technology standpoint, and in our everyday uses for it. Originally used for person-to-person (P2P) communication, i.e., Sally sends a text message to Betty – mobile messaging now offers tremendous value to businesses for customer and empl...
Oct. 5, 2015 01:15 PM EDT Reads: 158
SYS-CON Events announced today that ProfitBricks, the provider of painless cloud infrastructure, will exhibit at SYS-CON's 17th International Cloud Expo®, which will take place on November 3–5, 2015, at the Santa Clara Convention Center in Santa Clara, CA. ProfitBricks is the IaaS provider that offers a painless cloud experience for all IT users, with no learning curve. ProfitBricks boasts flexible cloud servers and networking, an integrated Data Center Designer tool for visual control over the cloud and the best price/performance value available. ProfitBricks was named one of the coolest Clo...
Oct. 5, 2015 01:00 PM EDT Reads: 724
“The Internet of Things transforms the way organizations leverage machine data and gain insights from it,” noted Splunk’s CTO Snehal Antani, as Splunk announced accelerated momentum in Industrial Data and the IoT. The trend is driven by Splunk’s continued investment in its products and partner ecosystem as well as the creativity of customers and the flexibility to deploy Splunk IoT solutions as software, cloud services or in a hybrid environment. Customers are using Splunk® solutions to collect and correlate data from control systems, sensors, mobile devices and IT systems for a variety of Ind...
Oct. 5, 2015 12:00 PM EDT Reads: 572
Organizations already struggle with the simple collection of data resulting from the proliferation of IoT, lacking the right infrastructure to manage it. They can't only rely on the cloud to collect and utilize this data because many applications still require dedicated infrastructure for security, redundancy, performance, etc. In his session at 17th Cloud Expo, Emil Sayegh, CEO of Codero Hosting, will discuss how in order to resolve the inherent issues, companies need to combine dedicated and cloud solutions through hybrid hosting – a sustainable solution for the data required to manage I...
Oct. 5, 2015 12:00 PM EDT Reads: 420
You have your devices and your data, but what about the rest of your Internet of Things story? Two popular classes of technologies that nicely handle the Big Data analytics for Internet of Things are Apache Hadoop and NoSQL. Hadoop is designed for parallelizing analytical work across many servers and is ideal for the massive data volumes you create with IoT devices. NoSQL databases such as Apache HBase are ideal for storing and retrieving IoT data as “time series data.”
Oct. 5, 2015 11:45 AM EDT Reads: 447
Clearly the way forward is to move to cloud be it bare metal, VMs or containers. One aspect of the current public clouds that is slowing this cloud migration is cloud lock-in. Every cloud vendor is trying to make it very difficult to move out once a customer has chosen their cloud. In his session at 17th Cloud Expo, Naveen Nimmu, CEO of Clouber, Inc., will advocate that making the inter-cloud migration as simple as changing airlines would help the entire industry to quickly adopt the cloud without worrying about any lock-in fears. In fact by having standard APIs for IaaS would help PaaS expl...
Oct. 5, 2015 11:30 AM EDT Reads: 435
As more and more data is generated from a variety of connected devices, the need to get insights from this data and predict future behavior and trends is increasingly essential for businesses. Real-time stream processing is needed in a variety of different industries such as Manufacturing, Oil and Gas, Automobile, Finance, Online Retail, Smart Grids, and Healthcare. Azure Stream Analytics is a fully managed distributed stream computation service that provides low latency, scalable processing of streaming data in the cloud with an enterprise grade SLA. It features built-in integration with Azur...
Oct. 5, 2015 10:00 AM EDT Reads: 730
Apps and devices shouldn't stop working when there's limited or no network connectivity. Learn how to bring data stored in a cloud database to the edge of the network (and back again) whenever an Internet connection is available. In his session at 17th Cloud Expo, Bradley Holt, Developer Advocate at IBM Cloud Data Services, will demonstrate techniques for replicating cloud databases with devices in order to build offline-first mobile or Internet of Things (IoT) apps that can provide a better, faster user experience, both offline and online. The focus of this talk will be on IBM Cloudant, Apa...
Oct. 5, 2015 09:45 AM EDT Reads: 436
SYS-CON Events announced today that HPM Networks will exhibit at the 17th International Cloud Expo®, which will take place on November 3–5, 2015, at the Santa Clara Convention Center in Santa Clara, CA. For 20 years, HPM Networks has been integrating technology solutions that solve complex business challenges. HPM Networks has designed solutions for both SMB and enterprise customers throughout the San Francisco Bay Area.
Oct. 5, 2015 09:00 AM EDT Reads: 563
As enterprises capture more and more data of all types – structured, semi-structured, and unstructured – data discovery requirements for business intelligence (BI), Big Data, and predictive analytics initiatives grow more complex. A company’s ability to become data-driven and compete on analytics depends on the speed with which it can provision their analytics applications with all relevant information. The task of finding data has traditionally resided with IT, but now organizations increasingly turn towards data source discovery tools to find the right data, in context, for business users, d...
Oct. 5, 2015 08:00 AM EDT Reads: 376
SYS-CON Events announced today that MobiDev, a software development company, will exhibit at the 17th International Cloud Expo®, which will take place November 3-5, 2015, at the Santa Clara Convention Center in Santa Clara, CA. MobiDev is a software development company with representative offices in Atlanta (US), Sheffield (UK) and Würzburg (Germany); and development centers in Ukraine. Since 2009 it has grown from a small group of passionate engineers and business managers to a full-scale mobile software company with over 150 developers, designers, quality assurance engineers, project manage...
Oct. 5, 2015 05:00 AM EDT Reads: 726
Learn how IoT, cloud, social networks and last but not least, humans, can be integrated into a seamless integration of cooperative organisms both cybernetic and biological. This has been enabled by recent advances in IoT device capabilities, messaging frameworks, presence and collaboration services, where devices can share information and make independent and human assisted decisions based upon social status from other entities. In his session at @ThingsExpo, Michael Heydt, founder of Seamless Thingies, will discuss and demonstrate how devices and humans can be integrated from a simple clust...
Oct. 4, 2015 12:00 PM EDT Reads: 623
SYS-CON Events announced today that Cloud Raxak has been named “Media & Session Sponsor” of SYS-CON's 17th Cloud Expo, which will take place on November 3–5, 2015, at the Santa Clara Convention Center in Santa Clara, CA. Raxak Protect automates security compliance across private and public clouds. Using the SaaS tool or managed service, developers can deploy cloud apps quickly, cost-effectively, and without error.
Oct. 3, 2015 01:15 PM EDT Reads: 582
Who are you? How do you introduce yourself? Do you use a name, or do you greet a friend by the last four digits of his social security number? Assuming you don’t, why are we content to associate our identity with 10 random digits assigned by our phone company? Identity is an issue that affects everyone, but as individuals we don’t spend a lot of time thinking about it. In his session at @ThingsExpo, Ben Klang, Founder & President of Mojo Lingo, will discuss the impact of technology on identity. Should we federate, or not? How should identity be secured? Who owns the identity? How is identity ...
Oct. 3, 2015 11:00 AM EDT Reads: 416