Primer: Model View Controller (MVC)

Primer: Model View Controller (MVC)

A short primer on the Model View Controller design pattern employed by concrete5


Article by Ollie / / Comments / Difficulty 
Primer: Model View Controller (MVC)

Model View Controller, or MVC, is a coding design pattern which aims to separate the key components of a web application for ease of development and maintenance. Similar patterns exist which dispense with the 'model' layer, employing only controllers and views (VC) - the objective is the same however - logical organisation, and easy reuse, of code.

This primer looks at MVC for completeness.

Models

Models can be described as classes which focus on making data available to the application. Instinctively, when we think of data, we think of SQL and database routines, and very often this is what a model will comprise. However, data can be obtained from many sources not just databases, and it would be just as appropriate for a Model to include methods which access external APIs or CSV files. Whatever the data's source, operations which manage data should all be organised in a Model.

Controllers

Controllers handle our application logic. If the user does X what should the application do? This could involve updating the View, i.e save confirmation, or it could involve taking input from the user and using that as the basis for request to a Model to return data to the View.

A Controller handles requests from the View, interacts with the Model and passes data back to the View.

Views

Views are reserved for presentation. Very often the View is nothing more than a HTML template, with little to no server-side code included, other than the minimum required to output content.

To summarise, MVC provides for logical separation of the different types of code than make up an application. By keeping the View as free of server-side code as possible, and coding all our application logic in the Controller and our data maintenance routines in the Model, we not only make it easier for Designers and Developers to work together, we also make the application easier to maintain and debug. It's also much easier to reuse components of an MVC application in other projects.

If you're not used to working in an MVC way, initially this can seem like a lot of effort, particularly for smaller applications, but, if you're prepared to invest a little time designing your application in a MVC or even VC type way, you'll reap the benefits later when you're asked to extend that application, and with each application be collating a suite of Controller and Model libraries you can drop into other applications you build, with the minimum of effort.

Join the conversation

comments powered by Disqus