Modern sites are interactive and dynamic - they react to the user's actions, process requests, and produce results. This is how many online services work, such as online banking or streaming platforms. The MVC is an architectural pattern usually used to create interactive and dynamic sites. This is another post about MVC, attempting to simplify the understanding.
What is MVC: Theory
A static HTML page doesn't know how to react to user actions. Two-way interaction requires dynamic web pages. MVC is the key to understanding dynamic web application development, so a developer needs to know this concept.
MVC is a concept or programming paradigm that stands for Model-View-Controller. It is a way of organizing source code that separates the blocks responsible for different tasks. One block is responsible for the application data, another block is responsible for the appearance, and the third block controls the application.
MVC Components:
Model - This component is responsible for the data and defines the application's structure. For example, if you create a To-Do application, the model component code will define the task list and individual tasks.
View - This component is responsible for interacting with the user. That is, the view component code defines the user interface of the application and how it is used.
Controller - This component is responsible for the communication between the model and the view. The controller code decides how the website reacts to the user. In other words, it is the brain of the MVC application.
Advantages of MVC Pattern
The MVC pattern brings a lot of advantages to the table, some of which are discussed below.
Scalability: The MVC pattern makes adding more resources to an application easier. This is because the model, view, and controller are entirely independent of each other and don't have to be modified when new resources are added to the application. This enables developers to add new resources to the application, such as new servers, new databases, etc., without having to refactor the application's code.
Maintainability: Another advantage of using the MVC pattern is better maintainability. The three components of the MVC pattern are self-contained, making it easy to troubleshoot issues and make changes.
Better Code Quality: Since the MVC pattern is widely used, many resources are available on the internet to help developers implement it. Moreover, plenty of tools make it easier for developers to create applications using the MVC pattern.
How MVC is like a sandwich shop
Imagine coming to a store or cafe where you can order a sandwich. There are tuna, turkey, and ham sandwiches on the menu. You order a turkey sandwich. The seller understands you from half a word, turns toward the kitchen, and tells the cooks to make a turkey sandwich.
The cooks have various products on hand: tuna, turkey, ham, cheese, lettuce, and other ingredients to add to the sandwiches. They pick just what they need for your turkey sandwich. You get your order.
We can describe the purchase of the sandwich through the MVC:
Model: the kitchen where the cook makes the sandwich
View: the finished sandwich that you are happy to eat
Controller: the vendor or bartender who takes the order and passes it on to the kitchen
You already visualized a prepared turkey sandwich when you ordered it from the bartender. This is called View.
In the same way, you can imagine interacting with a website. When you go to Google and search for "sandwich shop near me", you expect to see a list of websites and map locations as a search result.
When you hit "Enter", the browser sends the request to Google's servers. It includes the request to READ the list of available resources matching "sandwich shop" near your IP address or mobile device's current location. This request is similar to making a turkey sandwich order and is called the Controller.
Once received, the request is processed on Google's server. The program pulls all the relevant businesses selling sandwiches from the database to show the list. This can be compared to the kitchen and cooks in the sandwich example and is called a Model.
The Google server takes the matching shops from the database and prepares your order: a list of texts, links, and images. That's what the cooks in the sandwich store kitchen were doing. It's a View again.
MVC concept in Web Development
How the Controller works
The controller handles incoming requests. In the framework, this can consist of defining the specific URLs (routers) the user reaches when they click a link or a button. Consider this with the example of a site that gives the user a list of his friends:
Click to website.com/profile/ ->
returns profilewebsite.com/friends/ ->
returns friendswebsite.com/friend={userName}/ ->
returns the profile of a particular friend
How the Model works
The Model is responsible for the data stored and processed on the server. It will listen to the Controller and retrieve or update the database based on the request (GET/POST/PUT/DELETE). User: { userName: { firstName, lastName }, friends }
Here is an example of a Mongoose user Schema in MongoDB, ensuring data consistency.
// 1. Referencing Mongoose
const mongoose = require('mongoose')
// 2. Defining the Schema
const UserSchema = new mongoose.Schema({
userName: { type: String, unique: true },
email: { type: String, unique: true },
password: String
})
// 3. Exporting a Model
module.exports = mongoose.model('User', UserSchema)
Mongoose is an Object Data Modeling (ODM) library for MongoDB and Node.js. It manages relationships between data, provides schema validation, and is used to translate between objects in code and the presentation of those objects in MongoDB.
While MongoDB is schema-less and accepts any type of data, it is a good practice to create a Schema to reject inconsistent data inputs.
How the View works
The View is the combination of an HTML template (e.g., EJS, Pug, ReactJS) and CSS that the server returns after processing the request. You get a web page listing friends if the request is processed correctly. If the request is invalid, you get a 404 error page. ```
Friend 1: {friendList[0].userName}
Friend 2: {friendList[1].userName}
Friend 3: {friendList[2].userName}
...
Implementing the MVC Pattern
This section will discuss how to use MVC pattern in a web application. Let's assume we want to build an e-commerce application for an online computer store. And let's further assume that we want to display the details of a computer on the homepage. We will use the following domain terms to discuss the implementation of the MVC pattern in our application.
MVC Architecture in Different Programming Languages
The MVC pattern can be implemented in various programming languages. Let's discuss how the MVC pattern is implemented in some popular programming languages.
JavaScript: The Node.js framework follows the MVC pattern.
Python: The Django framework follows the MVC pattern.
Ruby: The Ruby on Rails framework is designed to implement the MVC pattern. However, the application's structure may vary slightly from other Ruby MVC frameworks such as Sinatra and Grape.
Java: The Spring Framework follows the MVC pattern.
PHP: The Laravel framework follows the MVC pattern.
C#: The ASP.NET MVC framework follows the MVC pattern.
Scaling Applications with the MVC Pattern
The MVC pattern is the most widely used architectural pattern for developing robust and scalable applications. However, it must be appropriately designed to scale an application with the MVC design pattern. Let's understand how we can do that.
Model: The model may contain database tables containing the application's data. If the database tables have many records, we need to store the data in a database that can handle large amounts of data. If the database tables have a low number of records, we can store the data in a database that can handle a low number of records.
View: The view may contain the front-end code of the application (user interface). The front-end code is responsible for the interactions of the user and the data displayed on the screen. The front-end code should be decoupled from the database so other applications or software can reuse it.
Controller: The model may contain the database containing the data displayed on the screen. If the database is small, the controller can directly fetch the data from the database and pass it to the view. However, if the database is large, the controller should fetch data from the model that can handle large amounts of data and store the data in a database that can handle a low number of records.
Best Practices for Using the MVC Pattern
While the MVC pattern is widely used, it is important to use it correctly. Here are a few best practices to help you implement the MVC pattern more effectively.
Make sure all your business logic is stored in the model. Do not put any business logic in the controller or the view. This will make the application more scalable and easier to maintain.
Use independent components in the application. This will help the application scale better.
Use a database that can handle a large volume of data. This will help in scaling the application.
Conclusion
MVC is an approach to application design that involves separating code into blocks of model, view, and controller types. The Controller processes incoming requests. The Model retrieves the information needed to execute specific queries from the database. The View defines the result of the request that the user receives.
MVC not only allows abstracting the server and the database from the user but also helps structure the app so that it is easier to navigate during development and simplify the team collaboration process on various parts of the web application. For example, if you want to change the templating language from EJS to Pug, you go into the Views folder and have everything isolated. To change the database from MongoDB to SQL, you go to Models without stressing about breaking Controllers or Views.
Inspired by the following sources: