by Adil Raqioui

Project: MVC folders architecture

Model-View-Controller (MVC) is one of the many architectural patterns used in software development. It helps organize your project structure clearly and understandably, which is particularly useful in flexible frameworks like Express.js. Not only does it help organize your code, but it also defines the flow of the request cycle. How? Let’s dive into our story :)

The Request Cycle in the MVC Pattern:

Meet Mohammed, a user who decides to visit a random website. Little does he know, this website is using MVC architecture. As his request arrives at the server, the action begins😱.

When the request reaches the server, the server needs to determine where to send it. This is where the router comes in. The router's role is to map incoming requests to their appropriate endpoints. We define methods for each HTTP method, like GET to retrieve data, POST to send data, PUT to update data, and so on. These methods handle the router's logic or request processing.

Here, we encounter our first key concept: the Controller. The Controller’s role is to manage the request logic. In Mohammed’s case, he wants to retrieve data. The request is routed to the GET method on the server. Within the Controller, the server needs to fetch some data from the database, which leads us to the Model. The Model is responsible for interacting with the database and retrieving the required data.

Once the Model has fetched the data, it sends it back to the Controller. Now, everything is almost ready, but there’s one final step: displaying the data to the user. Express.js has the capability to send HTML to the browser, but since the data is dynamic, we need a way to embed this dynamic data into the HTML. This is where the View comes into play.

The View is like an HTML template where we can insert variables to represent our dynamic data. If you’re familiar with JSX syntax, it’s quite similar. In Express.js, we can use different templating engines like EJS, Pug, or Handlebars to render these views. For example, in an Express app, we can set the view engine like this:

app.set("view engine", "**ejs"**);
app.set("view engine", "pug");

Now, with everything set up, the response is ready to be sent back to Mohammed, who is now happily viewing the data on his browser 🥳.

Not a bad ending, right? Hehheeee 😄