Beyond Code: The Artistry of MVC in Crafting Dynamic Applications
Tags: javascript, webdev, architecture, programming
Published: 2024-05-24 13:21:04

Before delving into the concept of MVC architecture, allow me to share a story from a few years ago when I was sitting with my friend Hamza. At that time, I didn't know the importance and use of architecture in the world of software. We were discussing a problem related to a middleware function, and my code wasn't organized either - I had used routes, controllers, and middleware in the same JavaScript file. After hours of effort, we were successfully able to fix the errors. But suddenly, Hamza pointed out that the error still persisted. I argued that the code was running, but he responded, "You 'chapi master' (a person who is a master of doing things in a shorter way), haven’t you heard about MVC architecture?" My answer was no. After that, I studied the whole architecture.

So, what exactly is MVC architecture? Let me explain with a real-world example before we delve into the technical details.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/nit31ky1i6zkcdcu2vg2.png)
So, the picture above illustrates a restaurant scenario where a customer selects a dish from the menu and informs the waiter of their choice. The waiter, in turn, is aware of the restaurant's inventory. If the requested item is unavailable, such as a mocktail when the necessary ingredients are absent, the waiter informs the customer accordingly. Conversely, if the item is available, the waiter proceeds to the chef to prepare the desired food.
Here, the customer is like someone watching or looking at what's on display. The waiter is like the one in charge, sort of like the brain, making sure everything runs smoothly. They can check and manage tasks. In MVC, think of the chef as the model. The chef is like the person with all the ingredients needed to cook the food.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/89xnx43m4u9kie0ipfo4.png)
So above picture is the technical explanation of MVC architecture. Now we study them in depth with codes.
**View:**
•	The View of MVC architecture is the user interface (UI) of your application. The UI is what a user sees on their device when they interact with your program. The state of the View relies on the data stored using the mode
•	Multiple views can exist for a single model for various purposes
•	If you are a MERN stack developer, then React.js will act as the View because it will be displaying content to the user
•	For java users the view will be like this 

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/w71uw9zoitdk6xsskxra.png)
This above code represents how the data should be displayed to the user. Contains a method (printStudentDetails) to print the student’s name and roll number.
**Model :**
•	 It represents data that is being transferred between controller components or any other related business logic
•	For MERN stack users the model will be like this :

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/eh15oxsl69763q1uia0d.png)
A model is like the schema that you create for your project. It is obvious that fields such as 'filename' and 'data,' as mentioned in the above code, will be created in your database. For this particular code, I have used MySQL as my database.
•	In many software development frameworks and architectures like MVC , models are indeed connected to databases
**Controllers :**
•	receives user input and initiates a response by making calls on model objects
•	For MERN stack users the model will be like this :

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/0gi6eggcz9dkonn1uukm.png)
Keeping the schema that I have established in the model in mind, consider the above function (uploadFile) to act as a controller. As you can observe, multiple validations are being performed on it. It functions as the brain of your project, making crucial decisions.
•	The Controller is that part of the application that handles the user interaction. The controller interprets the mouse and keyboard inputs from the user, informing the model, and the view to change as appropriate.
**Routes :**
•	Routes are a crucial part of many web development frameworks that follow the MVC (Model-View-Controller) architecture. In MVC, routes typically fall under the "Controller" part of the architecture. But in most cases we  make a separate file for our routes 
•	Routes define the URL endpoints of your web application.
•	Routes are responsible for mapping HTTP request methods (GET, POST, PUT, DELETE, etc.) to controller actions.
•	They can handle parameters and route patterns, allowing for dynamic routing based on user input.
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/vu3i6rq9qqwxbnyesf3m.png)
In the above code “/upload” is your end point “uploadFile” is your controller that is coming from the variable “fileController” and “checkAuth” is your middleware.
**Behold, the moment you've been waiting for: introducing the middleware function, the backbone of seamless request handling and data manipulation!**
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/th5e6vykmi6czdcpwobm.png)

**Middleware function:**
In the beginning, middleware might confuse you. I was also confused at first, but with time, you'll grasp the concept of middleware. I intend to create a separate blog post about middleware and APIs as well. However, for now, let's focus on middleware.
Imagine planning a trip to the USA. When booking your flight, there's a higher chance you'll find an indirect flight that first stops in Dubai or Qatar before reaching the USA.
Congratulations! Through this brief analogy, you've grasped both the concepts of APIs and middleware. Trust me, it's as simple as planning this trip.
Now let me explain this analogy in technical way dubai is your middleware and your whole journey is API. Middleware functions usually have 3 standard params ( req, res, and next). The first two are objects, the last is a function that will call the next middleware function, if there is one.
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/y15bcivgt2jhjp5mjhxc.png)
The above code is middleware that acts as authentication for users. Now, the question arises: how can you use this middleware? Don't worry, I'm still here to guide you. Simply require the module and store it in a variable. Then, place it in your desired route.
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ikxf9jchkmum8iq3q5nz.png)
For instance I want to authenticate the user who is sending post request.
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/vkhek2q12uv8ry0z10gj.png)