|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?
Cloud based infrastructure deployment is becoming more and more appealing to customers, from Fortune 500 companies to SMEs due to its pay-as-you-go model. Enterprise storage vendors are able to reach out to these customers by integrating in cloud based deployments; this needs adaptability and interoperability of the products confirming to cloud standards such as OpenStack, CloudStack, or Azure. As compared to off the shelf commodity storage, enterprise storages by its reliability, high-availabil...
Oct. 27, 2016 05:45 AM EDT Reads: 1,250
The IoT industry is now at a crossroads, between the fast-paced innovation of technologies and the pending mass adoption by global enterprises. The complexity of combining rapidly evolving technologies and the need to establish practices for market acceleration pose a strong challenge to global enterprises as well as IoT vendors. In his session at @ThingsExpo, Clark Smith, senior product manager for Numerex, will discuss how Numerex, as an experienced, established IoT provider, has embraced a ...
Oct. 27, 2016 05:30 AM EDT Reads: 1,212
The Internet of Things (IoT), in all its myriad manifestations, has great potential. Much of that potential comes from the evolving data management and analytic (DMA) technologies and processes that allow us to gain insight from all of the IoT data that can be generated and gathered. This potential may never be met as those data sets are tied to specific industry verticals and single markets, with no clear way to use IoT data and sensor analytics to fulfill the hype being given the IoT today.
Oct. 27, 2016 04:45 AM EDT Reads: 2,875
Donna Yasay, President of HomeGrid Forum, today discussed with a panel of technology peers how certification programs are at the forefront of interoperability, and the answer for vendors looking to keep up with today's growing industry for smart home innovation. "To ensure multi-vendor interoperability, accredited industry certification programs should be used for every product to provide credibility and quality assurance for retail and carrier based customers looking to add ever increasing num...
Oct. 27, 2016 04:00 AM EDT Reads: 772
In his general session at 19th Cloud Expo, Manish Dixit, VP of Product and Engineering at Dice, will discuss how Dice leverages data insights and tools to help both tech professionals and recruiters better understand how skills relate to each other and which skills are in high demand using interactive visualizations and salary indicator tools to maximize earning potential. Manish Dixit is VP of Product and Engineering at Dice. As the leader of the Product, Engineering and Data Sciences team a...
Oct. 27, 2016 03:45 AM EDT Reads: 739
In the next forty months – just over three years – businesses will undergo extraordinary changes. The exponential growth of digitization and machine learning will see a step function change in how businesses create value, satisfy customers, and outperform their competition. In the next forty months companies will take the actions that will see them get to the next level of the game called Capitalism. Or they won’t – game over. The winners of today and tomorrow think differently, follow different...
Oct. 27, 2016 03:45 AM EDT Reads: 1,113
“Media Sponsor” of SYS-CON's 19th International Cloud Expo, which will take place on November 1–3, 2016, at the Santa Clara Convention Center in Santa Clara, CA. CloudBerry Backup is a leading cross-platform cloud backup and disaster recovery solution integrated with major public cloud services, such as Amazon Web Services, Microsoft Azure and Google Cloud Platform.
Oct. 27, 2016 03:45 AM EDT Reads: 1,509
The security needs of IoT environments require a strong, proven approach to maintain security, trust and privacy in their ecosystem. Assurance and protection of device identity, secure data encryption and authentication are the key security challenges organizations are trying to address when integrating IoT devices. This holds true for IoT applications in a wide range of industries, for example, healthcare, consumer devices, and manufacturing. In his session at @ThingsExpo, Lancen LaChance, vic...
Oct. 27, 2016 03:30 AM EDT Reads: 3,849
What are the successful IoT innovations from emerging markets? What are the unique challenges and opportunities from these markets? How did the constraints in connectivity among others lead to groundbreaking insights? In her session at @ThingsExpo, Carmen Feliciano, a Principal at AMDG, will answer all these questions and share how you can apply IoT best practices and frameworks from the emerging markets to your own business.
Oct. 27, 2016 03:00 AM EDT Reads: 2,697
Big Data has been changing the world. IoT fuels the further transformation recently. How are Big Data and IoT related? In his session at @BigDataExpo, Tony Shan, a renowned visionary and thought leader, will explore the interplay of Big Data and IoT. He will anatomize Big Data and IoT separately in terms of what, which, why, where, when, who, how and how much. He will then analyze the relationship between IoT and Big Data, specifically the drilldown of how the 4Vs of Big Data (Volume, Variety,...
Oct. 27, 2016 02:45 AM EDT Reads: 1,595
SYS-CON Events announced today that SoftNet Solutions will exhibit at the 19th International Cloud Expo, which will take place on November 1–3, 2016, at the Santa Clara Convention Center in Santa Clara, CA. SoftNet Solutions specializes in Enterprise Solutions for Hadoop and Big Data. It offers customers the most open, robust, and value-conscious portfolio of solutions, services, and tools for the shortest route to success with Big Data. The unique differentiator is the ability to architect and ...
Oct. 27, 2016 02:15 AM EDT Reads: 1,130
For basic one-to-one voice or video calling solutions, WebRTC has proven to be a very powerful technology. Although WebRTC’s core functionality is to provide secure, real-time p2p media streaming, leveraging native platform features and server-side components brings up new communication capabilities for web and native mobile applications, allowing for advanced multi-user use cases such as video broadcasting, conferencing, and media recording.
Oct. 27, 2016 02:00 AM EDT Reads: 4,259
The Internet of Things will challenge the status quo of how IT and development organizations operate. Or will it? Certainly the fog layer of IoT requires special insights about data ontology, security and transactional integrity. But the developmental challenges are the same: People, Process and Platform and how we integrate our thinking to solve complicated problems. In his session at 19th Cloud Expo, Craig Sproule, CEO of Metavine, will demonstrate how to move beyond today's coding paradigm ...
Oct. 27, 2016 02:00 AM EDT Reads: 3,972
DevOps is being widely accepted (if not fully adopted) as essential in enterprise IT. But as Enterprise DevOps gains maturity, expands scope, and increases velocity, the need for data-driven decisions across teams becomes more acute. DevOps teams in any modern business must wrangle the ‘digital exhaust’ from the delivery toolchain, "pervasive" and "cognitive" computing, APIs and services, mobile devices and applications, the Internet of Things, and now even blockchain. In this power panel at @...
Oct. 27, 2016 01:45 AM EDT Reads: 2,148
A completely new computing platform is on the horizon. They’re called Microservers by some, ARM Servers by others, and sometimes even ARM-based Servers. No matter what you call them, Microservers will have a huge impact on the data center and on server computing in general. Although few people are familiar with Microservers today, their impact will be felt very soon. This is a new category of computing platform that is available today and is predicted to have triple-digit growth rates for some ...
Oct. 27, 2016 01:00 AM EDT Reads: 34,306
In past @ThingsExpo presentations, Joseph di Paolantonio has explored how various Internet of Things (IoT) and data management and analytics (DMA) solution spaces will come together as sensor analytics ecosystems. This year, in his session at @ThingsExpo, Joseph di Paolantonio from DataArchon, will be adding the numerous Transportation areas, from autonomous vehicles to “Uber for containers.” While IoT data in any one area of Transportation will have a huge impact in that area, combining sensor...
Oct. 27, 2016 12:00 AM EDT Reads: 1,128
Almost everyone sees the potential of Internet of Things but how can businesses truly unlock that potential. The key will be in the ability to discover business insight in the midst of an ocean of Big Data generated from billions of embedded devices via Systems of Discover. Businesses will also need to ensure that they can sustain that insight by leveraging the cloud for global reach, scale and elasticity.
Oct. 27, 2016 12:00 AM EDT Reads: 11,136
SYS-CON Media announced today that @WebRTCSummit Blog, the largest WebRTC resource in the world, has been launched. @WebRTCSummit Blog offers top articles, news stories, and blog posts from the world's well-known experts and guarantees better exposure for its authors than any other publication. @WebRTCSummit Blog can be bookmarked ▸ Here @WebRTCSummit conference site can be bookmarked ▸ Here
Oct. 26, 2016 11:30 PM EDT Reads: 9,764
SYS-CON Events announced today that LeaseWeb USA, a cloud Infrastructure-as-a-Service (IaaS) provider, will exhibit at the 19th International Cloud Expo, which will take place on November 1–3, 2016, at the Santa Clara Convention Center in Santa Clara, CA. LeaseWeb is one of the world's largest hosting brands. The company helps customers define, develop and deploy IT infrastructure tailored to their exact business needs, by combining various kinds cloud solutions.
Oct. 26, 2016 11:00 PM EDT Reads: 3,929
Most people haven’t heard the word, “gamification,” even though they probably, and perhaps unwittingly, participate in it every day. Gamification is “the process of adding games or game-like elements to something (as a task) so as to encourage participation.” Further, gamification is about bringing game mechanics – rules, constructs, processes, and methods – into the real world in an effort to engage people. In his session at @ThingsExpo, Robert Endo, owner and engagement manager of Intrepid D...
Oct. 26, 2016 11:00 PM EDT Reads: 9,919