How MVC Works
Published:
By Andrew RutledgeA fun simulation to help understand the flow of MVC (Model, View, Controller) for Web Development created by Gemini
Interactive MVC Data Flow
Waiting for user request...
Scenario 1: The Page Load (GET Request)
This is the standard flow when a user types a URL into the browser or clicks a link. The goal is simply to retrieve and display information without changing anything in the database.
- The Request: The Browser asks the server for a specific page (e.g., viewing a specific snippet).
- The Brains: The Router matches the URL and hands it to the Controller.
- The Data Fetch: The Controller asks the Model to go into the Database and pull the requested snippet.
- The Presentation: The Model hands the raw data back to the Controller, which injects it into the HTML View and sends the final, rendered page back to the Browser.
Key Concept: GET requests are meant to be idempotent. This means you can refresh the page 100 times, and it will never accidentally duplicate data or break the database.
Scenario 2: The Form Submit (POST Request)
This flow is triggered when a user submits data back to the server, like adding a new snippet or updating a password. It requires a slightly more complex routing path to protect the database.
- The Request: The Browser sends a package of hidden data (POST) to the Router.
- The Validation: The Controller catches the data, checks it for errors (e.g., "Is the title blank?"), and hands the valid data to the Model.
- The Update: The Model executes an
INSERTorUPDATESQL query in the Database. - The Escape Route: Instead of loading a View right away, the Controller issues a Redirect.
The PRG Pattern (Post-Redirect-Get)
Notice how Step 7 in the simulation is a Redirect instead of sending data to the View? This is a crucial web development architecture known as the PRG Pattern.
If a Controller simply loaded a View after saving a form, the Browser would still remember the POST data. If the user accidentally hit the "Refresh" button on their browser, it would submit the form a second time, creating duplicate entries in the database!
By forcing a Redirect, the Controller wipes the Browser's memory of the form data and forces it to perform a brand new, safe GET request for the dashboard page. This completely eliminates the dreaded "Confirm Form Resubmission" browser warning.