The MVC design pattern separates business logic from user interface
Model–View–Controller is a design pattern or a software engineering concept that separates the model, the view and the controller from each others, thus dividing the labour in your application in such a way that:
The model is the brain, the knowledge, or simply data and means to using it:
- it knows where data is, how to access it and how to change it
- it responds to requests about data state
- it responds to instructions to change data state
The view holds the presentation logic like templating and caching, in a PHP MVC application it may range from a few html templates with PHP tags for inserting request specific data to a bunch of templates using a templating engine such as Smarty.
The controller acts as the mediator, like a front desk agent or the guy that takes your order and serves your dish at a McDonald’s:
- it receives the client (visitor’s browser) input in the form of GET or POST requests
- it could possibly verify and validate user input
- it instructs a the model to execute a specific action depending on the input it received
The Key benefits of using MVC
Separation of concerns
By separating the data logic (the model), the presentation logic (the view) and the application logic (the controller) you make sure that there is no interference between the three allowing you to work on and optimize each one dependently from the other two.
Let’s assume a scenario where we have a data driven website that we made with MVC in mind, this website needs a graphical redesign, we’ll simply hire an excellent web designer, which happens to be not so good at programming but we don’t care, all he will see is the website template files (our views).
Now we heard that PostgreSQL offers better performance and we want to switch from X to PostgreSQL, fine, all we have to do is migrate our database and modify our model, of course we will not modify a single line on the controller or view logic.
Data returned by the model is “pure” data, free from any formatting or presentation, when you need to present data to the user you write a view or more if you are offering the same data in many formats (HTML, XML, file for download…). The model is written only once and is reused by the views, there is no code duplication and you don’t waste your time rewriting code that does the same or almost the same thing.
By using MVC, you will end up having a library of well organized components that you can reuse on the same application and in other applications as well, this will drastically increase your productivity.
Part 2 : Writing a small PHP application with MVC (coming soon)…
In part 2 you will write your first MVC application, yes you will write models, views and controllers, it’s gonna be fun, so don’t miss it, subscribe to my RSS or follow me on the social network of your choice.