PHP MVC Part 1

Steven de Jong
21-09-2018

What is MVC

Nowadays, websites on the internet are interactive, dynamic and have a sort of function. They can be more than a static HTML/CSS site. This why the Model View Controller (MVC) pattern can be very handy.

Why use MVC

Business logic separated from the presentation: separated from concerns
Easier to reuse code so development is faster
Code is more organised, making it easier to understand, maintain, test and more secure.

What is a Model

In a Model you handle all the business logics, for example your stored data in a database.
The Model Layer is mostly made from three types of structures.

Domain Objects

Here you define how you must validate data before you handle an order or to calculate the total cost of your order.
Your Domain Objects are not yet aware of the storage, from where (database, API, files, etc.) and even if they get saved or retrieved.

Data Mappers

These objects are only responsible for the storage. Here you can find the SQL queries for retrieving, creating, deleting or editing data. You can also process data from an API here. Your Data Mappers will parsing the data from and to the API.

Services

Here you can make an interaction between Domain Objects and Data Mappers. You can avoid this, but then you will have to process some domain logics in your Controllers.

What is a View

Within your View layer you work with HTML or with a template engine like e.g. Blade, Smarty, Twig or Mustache.
From your controller you send to your View certain data that you can then retrieve and process here.

  • Also called “Presentation Layer”
  • Contains no business logic
  • Typically HTML, could also be used for e.g. JSON API’s and XML feeds

What is a Controller

Finally you have your Controller.
Within your Controller you communicate between your Models and your Views.
All data that must be available in your View for example, can be retrieved from your Models via your Controller.

  • Also called “Organisation Layer”
  • Coordinates the Model and View
  • Mediates UI interactions and updates to the Model

LEAVE A REPLY

you might also like