Skip to content

1. Using the MVC architecture in web applications/php

The PDF version of the document is available |HERE|.

The code for the document is available |HERE|.

The MVC model (Model-View-Controller) aims to clearly separate the presentation, processing, and data access layers. A web application following this model will be structured as follows:

Such an architecture is often called a 3-tier or 3-level architecture:

  • the user interface is the view (V)
  • the application logic is the controller (C)
  • the data sources are the model (M)

The user interface is often a web browser, but it could also be a standalone application that sends HTTP requests to the web service over the network and formats the results it receives. The application logic consists of scripts that process user requests. The data source is often a database, but it can also be simple flat files, a directory LDAP, a remote web service, etc. The developer should maintain a high degree of independence between these three entities so that if one of them changes, the other two do not have to change, or only minimally.

The MVC architecture is well-suited for web applications written in object-oriented languages. The PHP (4.x) language is not object-oriented. Nevertheless, we can make an effort to structure the code and the application architecture to align more closely with the MVC model:

  • The application’s business logic will be placed in modules separate from those responsible for managing the request-response dialogue. The MVC architecture becomes as follows:

In the [Logique Applicative] block, we can distinguish:

  • the main program or controller, which serves as the application’s entry point.
  • the [Actions] block, a set of scripts responsible for executing the actions requested by the user.
  • the [Classes métier] block, which contains the php modules necessary for the application’s logic. These are independent of the client. For example, the function that calculates a tax based on certain information provided as parameters does not need to concern itself with how that information was obtained.
  • The [Classes d'accès aux données] block, which groups the php modules that retrieve the data needed by the controller, often persistent data (BD, files, etc.)
  • the generators of the views sent as a response to the client.

In the simplest cases, the application logic is often reduced to two modules:

  • the [contrôle] module, which handles client-server communication: processing the request, generating various responses
  • the [métier] module, which receives data to be processed from the [contrôle] module and provides it with results in return. This [métier] module then manages access to the persistent data itself.