Previously, I covered the high level design of a web app with controllers and views.
But there’s one more piece of the Model-View-Controller, or MVC, puzzle to include: the M, models.
A recap of an application with controllers and views
The image above depicts an application utilizing: routes to associate URLs with controllers; controllers to handle those user requests; and views to render pages:
- Routes — associate URLs with controllers
- Controller — handle user requests
- View — render pages
- Model — ? (the missing piece)
And it shows controllers interacting directly with a database. But in a full web application, this is done using the final third of the MVC trio: models.
Adding models to the mix
Models act as the middlemen between your controllers and your database, and are leveraged by controllers to interact with the database.
Your app should ultimate have one model for every different object type in your application.
For example, if you were building an application based on cars, you may have two different object types:
In that case, you would create two models:
And each of those would be responsible for interacting with the database to retrieve any information for their respective object types — for example, the
Car model would retrieve all car-related info.
So let’s review the complete request-fulfilling loop, with models included.
The complete MVC request-fulfilling loop
A user enters a URL in their browser that points to a web application, thus making a request.
That URL is matched to a route, which associates the URL with a designated controller action (i.e. a function in a controller).
The controller leverages the necessary models — which interact with the database — to retrieve the necessary information.
It then sends that information off to a view, which renders the request page for the user to view in their browser.