MVC for Noobs
AKA, How to Organize Your Code
3 min read
What Exactly is MVC?
For the Nerds! 🤓
“Model–view–controller is a software architectural pattern commonly used for developing user interfaces that divide the related program logic into three interconnected elements.
This is done to separate internal representations of information from the ways information is presented to and accepted from the user.”
Source: Wikipedia - Model View Controller
For the Noobs! 👨🏫
Simply put, MVC is a way to organize your code.
As applications get larger and more complicated, it can be helpful to have a system in place to keep your codebase organized.
MVC organizes your application into three layers: Model, View Controller
By breaking up your app into different components we gain a ton of benefits. This is very similar to the separation of concerns we have in our frontend: HTML for content, CSS for style, and JS for interactivity.
It's as Easy as 1 - 2 - 3
1. Model - the data behind your app.
2. View - the look of your app.
3. Controller - the brains of your app.
Why Use MVC?
- Separation of Concerns: with your app separated into different components, you can focus on one aspect without affecting the others.
- Great for teams: multiple developers can work on each layer (model, view, controller) simultaneously.
- Adaptable: it's very easy to swap out different components without having to rewrite everything (e.g. replace EJS with Handlebars for your Views).
- Organized: given an outline to follow, MVC gives you an easy way to organize your code from the start.
Okay, Let's Dig In.
- The Model is the layer of your application that manages all of your data
- Defines the structure of the app's data
- At the request of the user (via a controller) the Model can find, update, manipulate, or add to the app's database storage
- The updated state of the application will then be passed back to the Controller which will update the View
- Examples of database storage include: MongoDB, MySQL, and PostgreSQL
- The View handles everything that is visible to the user, the “look” of your app
- The View also represents the visual interface between the app and the user
- The View and Model do not communicate directly with each other
- Templating engines include: EJS, Handlebars, and Knockout.JS
- The Controller is the “brain”
- When a request/action is made by the user, a controller is the layer responsible for how that request is handled
- There are some actions that need the Model to be updated (like adding a task in a To Do app) and the input from the user will be sent to the controller to update the Model
- Other actions may only require a different View of the same Model data (displaying To Do tasks with a deadline due tomorrow) and the Controller can handle this directly without updating/interacting with the Model
MVC - It's Like Throwing a Party
You have the one friend with the goods
You have the one friend who can connect everyone.
And, you have the one friend with a house.