Model View Controller (MVC) Explained

Model View Controller (MVC) Explained

What is MVC, and how can we use it to properly structure our full-stack applications?

ยท

2 min read

Model View Controller, or MVC for short, is an architectural pattern, where we structure our full-stack applications into three main components: the model, the view, and the controller.

Model

The Model refers to the data-related aspects of the application. This includes the schema of objects in your database. For example, a User model can contain all user-related data, such as user ID, username, and e-mail, while a BlogPost model can contain fields such as the author, title, content, and tags of a blog post.

View

The View refers to the UI logic of the application. This can include UI components like forms, navigation, buttons, and more. It can also include HTML pages.

Controller

The controller is what controls the flow of the application. It communicates to both the Model and View to handle requests and send responses. For example, a user can make a request through a form (View), which flows through the Controller, which modifies some data in the User model of the database (Model), and then returns a response to the View with a message stating that the user successfully updated their information. The controller contains all the server-side logic and can be thought of as a "middle man" of sorts.

How do the Model, View, and Controller work together?

Users make a request through the UI, or the View. This request is passed to the API, or server (Controller). The controller processes the request. If needed, it modifies the database (Model) and returns a response to the user.

MVC flow diagram

It is important to note that the View and Model do not directly communicate with each other; they communicate exclusively through the Controller.

Here is an example of a project built with the MVC architecture:

MVC folder structure example

We can see here that the project is clearly organized, separating the Model (/models), View (/views), and Controller (/controllers). There is even another layer of abstraction here, /routes, which further distinguishes different categories of controllers.

Summary

In sum, MVC is an architectural pattern designed to keep projects organized and maintain separation of concerns. The Controller communicates between the View, or the UI, and the Model, or the database-related logic. Structuring projects this way leads to code that is easy to read and maintain.

ย