MVC, What Is It?

MVC is often used as a buzzword, but what actually is it?

MVC (Model, View, Controller) is an architectural pattern used to separate a system into 3 different sections, each with their own responsibilities.

Model

The Model is responsible for gathering and storing data, and that is its only responsibility, this data could be from a file, feed, database or any other method of storing data.

View

The View is responsible for rendering what a user will see. It will be given some data by the controller, it should never change or process this data, and render this in an easy way for the user to view.

Controller

The Controller is responsible for gathering specific data and passing it to a view when requested by a user, or processing some data sent by the user then storing it using a model.

How does MVC work in practise?

Most web based systems will store data using a database, the system will have 1 model per database table. For example:

Let’s say a database has the tables: students, courses, student courses.

This system could be used to manage which students are present on which courses.

The system would then have the models: Student, Course. Each of these models would have several methods to access or store data in its respective table.

Note, a systems models do not have to exactly match the database, sometimes it may be easier or more convenient to have a model represent 2 or 3 tables that when accessed will return 1 dataset.

In this system we could have a page that allows you to edit a student, a user would go to this page by sending a request to the relevant controller, the controller would then use the Student model to retrieve the specific students data and pass this data to a view which would then render this data in an easy way for the user to view and edit. Once the user is finished editing the data they could send another request back to the system essentially saying that the student in question’s data needs to be updated with these new values. The controller would process this request, validate any data being persisted to the database and, if passed validation, persist this data to the database using a different method on the Student Model.