Follow the latest thinking from people working at the cutting edge of innovation and have your say on everything from economic policy to robot overlords.
by Tayyab
Posted on
MVC is a design pattern. A Design pattern is a code structure that allows for common coding frameworks to be replicated quickly. MVC stands for “Model View Controller”.
MVC is a concept that enables to separate business logic from the presentation. One of the biggest advantages is the code re-usability. There are other benefits, such as: designers edit the Views, without worrying that they will screw up database access logic.
The MVC pattern separates an application in 3 modules: Model, View and Controller:
It is database layer to interact with database and responsible to manage the data; it stores and retrieves entities used by an application and contains the logic implemented by the application. Each entity has its own model.
It is presentation layer responsible to display the data provided by the model in a specific format.
It is core layer to handle the model and view layers to work together. On request receive from client, controller invoke the model to perform the requested operations like insert, delete, update and get data related to current request and sends to the View.
The view receive the data and format it to be presented to the user in HTML format.
The application entry point will be “index.php”. The index php file will delegate all the requests to the controller:
The controller is the first thing which takes a request, parses it, initializes and invoke the model and takes the model response and sends it to the presentation layer. It’s practically the medium between the Model and the View.
Our Controller class has only one function and the constructor. The constructor instantiates a model class and when a request is done, the controller decides which data is required from the model. Then it calls the model class to retrieve the data. After that it calls the corresponding passing the data coming from the model.
The Model represents the data and the logic of an application, what many calls business logic. Usually, it’s responsible for:
In our example the model is represented by 2 classes: the “Model” class and a “Book” class. The model doesn’t need any other presentation. The “Book” class is an entity class. Their solely purpose is to keep data.
In the above snippet you can notice how Model is returning a specific book, or a list of all available books:
In our example the model layer includes the Book class. In a real scenario, the model will include all the entities and the classes to persist data into the database, and the classes encapsulating the business logic.
The above example is a simplified implementation in PHP. Most of the PHP web frameworks based on MVC have similar implementations, in a much better shape. However, the possibility of MVC pattern are endless.
The advantages of Model View Controller pattern: