The Model View controller pattern is the most used pattern for today's world Web applications. It has been used for the first time in Smalltalk and then adopted and popularized by Java. At present there is more than a dozen PHP Web frameworks based on MVC pattern.
Despite the fact that the MVC pattern is very popular in PHP and is hard to find a proper tutorial accompanied by a Urce code example. That's the purpose of this tutorial.
the MVC pattern separates an application in 3 Modules:model, View and Controller:
- The model is responsible to manage the data; It stores and retrieves entities used by an application, usually from a database, and contains the logic implemented by th E application.
- The view (presentation) is responsible to display of the data provided by the model in a specific format. It has a similar usage and the template modules present in some popular web applications, like WordPress, Joomla, ...
- The controller handles the model and view layers to work together. The controller receives a request from the client, invokes the model to perform the requested operations and sends the DAT A to the View. The view formats the data to is presented to the user, in a Web application as an HTML output.
The above figure contains the MVC collaboration Diagram, where the links and dependencies between figures can be observed:
Our short PHP example have a simple structure, putting each MVC module in one folder:
Controller
The controller is the first thing which takes a request, parses it, initializes and invoke the model and takes the model R Esponse and sends it to the presentation layer. It's practically the liant between the model and the view, a small framework where Model and view is plugged in. In our naive PHP implementation the controller was implemented by only one class, named unexpectedly controller. The application entry point would be index.php. The index PHP file would delegate all the requests to the controller:
// index.php File include_once ("controller/controller.php"); $controller New Controller (); $controller->invoke ();
Our Controller class have only one function and the constructor. The constructor instantiates a model class and when a request was done, the controller decides which data are required from The model. Then it calls the model class to retrieve the data. After then it calls the corresponding passing the data coming from the model. The code is extremely simple. Note that the controller does not know anything about the database or what's the page is generated.
include_once("model/model.php");classController { Public $model; Public function__construct () {$this->model =NewModel (); } Public functionInvoke () {if(!isset($_get[' Book '])) { //no special book is requested, we'll show a list of all available books $books=$this->model->getbooklist (); include' View/booklist.php '; } Else { //Show the requested book $book=$this->model->getbook ($_get[' Book ']); include' View/viewbook.php '; } }}
In the following MVC Sequence Diagram you can observe the flow during a HTTP request:
Model and Entity Classes
the Model represents the data and the logic of an application, which many calls business logic. Usually, it ' s responsible for:
- Storing, deleting, updating the application data. Generally it includes the database operations, but implementing the same operations invoking external Web services or APIs is not a unusual at all.
- encapsulating the application logic. The the layer that should implement all the logic of the application. The most common mistakes is to implement application logic operations inside the controller or the view (presentation) lay Er.
In our example the model was 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. This class should is exposed to the view layer and represents the format exported by the Model View. In a good implementation of the MVC pattern only entity classes should is exposed by the model and they should not ENCAPSU Late any business logic. Their solely purpose is to keep data. Depending on implementation Entity objects can is replaced by XML or JSON chunk of data. In the above snippet you can notice how Model was returning a specific book, or a list of all available books:
include_once("model/book.php");classModel { Public functiongetbooklist () {//Here goes some hardcoded values to simulate the database return Array( "Jungle Book" =NewBook ("Jungle book", "R. Kipling", "A Classic book."), "Moonwalker" +NewBook ("Moonwalker", "J. Walker", ""), "PHP for Dummies" =NewBook (' PHP For Dummies ', ' Some Smart guy ', ' "") ); } Public functionGetBook ($title) { //We use the previous function to get all of the books and then we return the requested one. In a real life scenario this is done through a DB Select command $allBooks=$this-getbooklist (); return $allBooks[$title]; } }
The example the model layer includes the book class. In a real scenario, the model would include all the entities and the classes to persist data into the database, and the CLA SSEs encapsulating the business logic.
classBook { Public $title; Public $author; Public $description; Public function__construct ($title,$author,$description) { $this->title =$title; $this->author =$author; $this->description =$description; } }
View (Presentation)
The view (presentation layer) is responsible for formating the data received from the model in a form accessible to the user . The data can come in different formats from the Model:simple objects (sometimes called Value objects), XML structures, JS On, ...
The view should not being confused to the template mechanism sometimes they work in the same manner and address similar issue S. Both would reduce the dependency of the presentation layer of from rest of the system and separates the presentation ele ments (HTML) from the code. The controller delegates the data from the model to a specific view element, usually associated to the main entity in the Model. For example the operation ' Display account ' would be associated to a ' Display account ' view. The view layer can use a template system to render the HTML pages. The template mechanism can reuse specific parts of the page:header, menus, footer, lists and tables, .... Speaking in the context of the MVC pattern
In we example the view contains only 2 files one for displaying one book and the other one for displaying a list of books .
<HTML><Head></Head><Body> <?php echo ' Title: ' $book->title. ' <br/> '; Echo ' Author: '. $book->author. ' <br/> '; Echo ' Description: '. $book->description. ' <br/> '; ?></Body></HTML>
booklist.php
<HTML><Head></Head><Body> <Table> <tbody><TR><TD>Title</TD><TD>Author</TD><TD>Description</TD></TR></tbody> <?php foreach ($books as $title = + $book) {echo ' <tr><td><a HRE F= "index.php?book=". $book->title. ' " > '. $book->title. ' </a></td><td> '. $book->author. ' </td><td> '. $book->description. ' </td></tr> '; } ?> </Table></Body></HTML>
The above example is a simplified implementation in PHP. Most of the PHP Web frameworks based on MVC has similar implementations, in a much better shape. However, the possibility of MVC pattern is endless. For example different layers can is implemented in different languages or distributed on different machines. AJAX applications can implements the View layer directly in Javascript in the browser, invoking JSON services. The controller can be partially implemented on client, partially on server ...
This
post should is ended before enumerating the advantages of Model View Controller pattern:
- The Model and View is separated, making the application more flexible.
- The Model and view can be changed separately, or replaced. For example a Web application can is transformed in a smart client application just by writing a new View module, or an AP Plication can use Web services in the backend instead of a database, just replacing the model module.
- Each module can be tested and debugged separately.
Model View Controller (MVC) in PHP