Understanding MVC is a very important thing to know if you want to be able to organize your apps in a very clean way.
So what is this MVC thing and why is it talked about so often?👀
In the simplest way put, MVC (Model View Controller) is a way of thinking when creating or structuring our applications. It's talked about often because it is one of the standard approaches when creating an application. Let's dive deeper on MVC in regards to web applications.
Let's break down MVC
Imagine someone goes on google and searches for all types of cars. There is two things I want you to pay attention to in the screenshots. The first is what the url looks like before the person clicks search and the second is after the user have clicked search.
URL Before the user clicks seacrh
Currently the URL is just 'https://www.google.com/'. Let's see what happens when the user clicks the search button to find information on cars.
URL After the user clicks search
It's obvious that you notice a huge difference between the two URLs so lets look at how MVC comes into play.
Router
So the router is part of the MVC pattern even though it doesn't have it's own specific letter in the acronym. The router has ONE job and it does it very well. The router job is to look at the URL (when the user makes a request) and pass that information along to the appropriate controller.
Let's look at some code!
The MVC model can apply to many different languages but let's use JavaScript (NodeJS/ExpressJS) for example.
So here we have a basic Node server:
const express = require('express')
const app = express()
const connectDB = require('./config/database')
**const homeRoutes = require('./routes/home')**
const todoRoutes = require('./routes/todos')
require('dotenv').config({path: './config/.env'})
connectDB()
app.set('view engine', 'ejs')
app.use(express.static('public'))
app.use(express.urlencoded({ extended: true }))
app.use(express.json())
**app.use('/', homeRoutes)**
app.use('/todos', todoRoutes)
app.listen(process.env.PORT, ()=>{
console.log('Server is running, you better catch it!')
})
You don't have to understand everything going on. Let's just focus on the two lines of code that's that is starred.
The first line:
const homeRoutes = require('./routes/home')
is essentially just importing a module and storing it in a variable to use later. The module in this sense is just a directory that's inside of your project.
So now that you know that, let's look at the next important line of code:
app.use('/', homeRoutes)
P.S. app.use is just middleware and middleware is just essentially what is happening (logic, functionality, etc.) in the MIDDLE of the request and response.
So this line is just saying "Hey server, when someone makes a request to the root route ('/' is the root route) go to the homeRoutes so our homeRoutes router can send this information to the appropriate controller". Remember homeRoutes is a variable that points to the module(directory in your project).
So when the user goes to the root route (ex: www.something.com/) the server knows what to do which is go to the router made for the root route. Now, let's look at what happens when we actually get to where the router is at.
P.S. the router is usually inside of a directory (folder) named Routes
Looking at our router
const express = require('express')
const router = express.Router()
const homeController = require('../controllers/home')
router.get('/', homeController.getIndex)
module.exports = router
I don't want to focus too much on the code but rather the high level concept so I will just focus on the most important part of the code.
router.get('/', homeController.getIndex)
This is the router. This is what knows what to do when a user make a request. This router is saying "Hmm, I see the user made a GET request to the root route and I know exactly what controller(homeController) to send this request to so that they can process this! Not only do I know the controller to send this to but I know the method that the controller is going to use to process this(getIndex)". Remember, the router ONLY JOB is to look at the URL (and what kind of request was made) and send that information to the appropriate controller to process.
P.S. remember the variable that was set in the server code to specify where the module (directory) is coming from? This is the same concept with the homeController variable
MV(C)- The C is for Controller
Before we look at code let's understand what the controller do. I like to look at the controller as the job of the "Middle Man" since it communicates with multiple parts of the application. The controller job is to take the request and process it based on the information of the request. Sometimes the controller receives the information from the router and only needs to talk to the view and sometimes it needs to talk to the model AND the view. In the simplest way put, the controller takes a request and converts that to commands the model and/or view can understand and process. Let's look at some code.
module.exports = {
getIndex: (req,res)=>{
res.render('index.ejs')
}
}
In this code, the controller received the information (request) from the router and this is HOW IT'S RESPONDING (Remember, everything on the internet is just requests and responses). So essentially it's just RENDERING A VIEW. So the controller is saying "Hey router thanks for that information, based on that request all I need to do is go tell the view what to do with this".
M(V)C - The V is for View
The view ONLY job is to take the information that the controller sends it and present that to the client (browser). In this case the view is just going to render some ejs which just spits out some html code. I think the view is the easiest to understand because this is what we see when we get on the internet everyday. This blog post you are reading is just a view! Now that we understand that. Let's look at the model.
(M)VC - The M is for Model
This can be intimidating to understand but I will try to make it as simple as possible! The model job is to define the data structure. The model is what talks to the database to get any information the controller asks for and also do any deleting, inserting, updating, or selecting from the database. Let's think about the google example from earlier. When someone search for cars and hit enter, the router sends the request to the controller and the controller ask the model "Hey model, can you give me ALL the information that you have on cars?" The model then checks the database and says "Here is all the information the database has stored".
I hope you now have a better understanding of how MVC works on a high level. If you are still confused please watch this video (https://www.youtube.com/watch?v=1IsL6g2ixak&t=639s) to help you better understand.
Feel free to give me a follow on these social sites:
Twitter: https://twitter.com/NickAHollins
LinkedIn: https://www.linkedin.com/in/nicholas-hollins/
Github: https://github.com/TheDevNick/TheDevNick
Top comments (1)
Thanks!