The MVC pattern on the server
Model, view and controller in a web application: who does what, the path of a request from the router to the response, and the classic layering mistakes.
- 22 cards
- 5 topics
- Free
The outline, topic by topic
Each topic is weighted the way the exam weighs it.
- Concepts
- Questions
- Sort and link
- Scenarios
- Understand
A few cards from the deck
Model: what is it?
Show the answer
The layer that holds the application's data and business rules, and that alone talks to the database.
Computing a discount or checking stock lives here. Since it knows nothing about HTTP, the same code serves a page, an import script and the tests.
Besides the controller's role, which layers' work does this action do?
```python
def show(request, id):
row = db.execute("SELECT * FROM articles WHERE id = ?", [id]).fetchone()
return "<h1>" + row["titre"] + "</h1>"`- The model (SQL) and the view (HTML)
- The model only, because of the SQL query
- The view only, because of the HTML string
- The router and the view, since the action receives
idand writes HTML
Show the answer
The model (SQL) and the view (HTML)
The action should read
id, callArticle.find(id)and pass the result to a template. Here it holds all three roles. Receivingiddoes not make it a router: the router extracted it before calling it. Another trap: iftitrecontains HTML, the page interprets it for lack of escaping.In MVC, only the … talks to the database and holds the business rules.
Show the answer
In MVC, only the model talks to the database and holds the business rules.
An SQL query written in a controller or in a view is a layering mistake: it is tied to display or HTTP and cannot be reused.
View: what is it?
Show the answer
The layer that formats the data received in order to show it, for instance as HTML, without changing its state.
It loops and tests in order to display, that is all. No SQL, no business rule: HTML can be replaced by JSON without touching anything else.
The price-with-discount calculation is copied into two templates, and one day they show different totals. Which fix respects the MVC split?
- Put it in a shared template that both pages include
- Leave it in the first page's controller, which the second one calls
- Add a test that compares the two totals after every change
- Put it in the model, called by the controller
Show the answer
Put it in the model, called by the controller
A business rule must exist once, in the model. The controller gets the result and the view displays it: both pages necessarily give the same total. A shared template would keep the calculation in the view, and a test would only report the gap.