05 - Introduction of MVC

Architecture of an application

An application can have one of the following three types of architecture:

1. Single tier

In single tier all the three layers (Presentation, business and data) are integrated and installed on single computer. If this application has to be accessed on multiple systems, different installation on separate system needed.

2. Two tier

In two tier architecture three layers are distributed on two systems Client and server. Presentation layer resides on client side. Data layer resides on server side. Business logic layer resides on either client side or server side: based on the integration of business layer this type of architecture can be classified in two types:

  • Fat client and thin server

In this type business layer is integrated with presentation layer at client side.

  • Fat server and thin client

In this type business layer is integrated with data layer at server side.

3. Three tier

In this type of application three layers are separately on three entities. Presentation layer at client side, business logic layer at application server and data layer at database server. This type of architecture is best for advance web applications. To improve the performance of applications, three layers follow the request response mechanism.

MVC stands for Model-View-Controller. It is a standard in web application design in today’s scenario.

The Model View Controller model is the latest application development model for developing desktop, mobile, and web applications. It is extremely useful in large applications because in MVC, different parts (views, business logic and data storage) of a system are developed separately. That is the result of loosely coupled modular application. Because of this model maintenance, flexibility, and scalability of a system increases and code becomes shorter and easier to read. A lot of PHP frameworks are based on MVC patterns which already exist like zend, codigniter.

What is PHP MVC Framework?

In PHP MVC Framework, the ‘html’ views, business logics controllers and data handling models are developed separately, enabling the designers and developers to work with the views without any concern with the data and its handling. This makes PHP application components loosely coupled.

Advantages of MVC model:

  1. It is a simple solution for most web applications.
  2. It is flexible and extensible.
  3. It supports advance application.
  4. It is best to manage application workflow.
  5. MVC model separate the code into three categories: Presentation, Business logic and Data access.
  6. Presentation code can be consolidated in one part of application, business logic in another and the data access in another one.
  7. It is the best suited model, if there is more than one developer working on the same application.
  8. Easy to test and maintenance

Model

It is the part of the application that defines the basic functionality behind a set of abstraction. Data access routines and some business logic can be defined in the model. The model can provide the view stored user data for presentation.

In PHP MVC Framework, the model is responsible for managing the data that involves the storage and retrieval of entities like the ‘user’ or a ‘product order’ from the database or stored arrays.

  1. A model is an object representing data or even activity, e.g. a database table.
  2. The model manages the behaviour and data of the application domain, responds to requests for information about its state and responds to instructions to change state.
  3. The model represents enterprise data and the business rules that govern access to and updates of this data. Often the model serves as a software approximation to a real-world process, so simple real-world modeling techniques apply when defining the model.
  4. The model is the piece that represents the state and low-level behaviour of the component. It manages the state and conducts all transformations on that state. The model has no specific knowledge of either its controllers or its views. The view is the piece that manages the visual display of the state represented by the model. A model can have more than one view.

Example

In the following code snippet a Book Selection model is represented by two classes ‘Book’ and ‘Model’. The ‘Book’ is an entity class that is used to keep the book’s data. The ‘model’ class is used to store and retrieve the book’s data.

Book Class and Model class

<?php
classBook
 {
    public $name;
    public $version;
    public $yearOfPublish;
    public function __construct ( $name, $version, $yearOfPublish )
    {
    $this -> name = $name;
    $this -> version = $version;
    $this -> yearOfPublish = $yearOfPublish;
    }
}
?>

<?php
classModel {
    public $text;
    public function __construct ( )
    {
        $this-> text = 'Book Selection';
    }
    public function getBookList( )
    {
        return array (
        'PHP for Beginners' => new Book ('PHP for Beginners', '1.0','1996'),
        'Introduction to PHP MVC' => new Book ('Introduction to PHP MVC','1.0', '2008'),
        'Advanced PHP' => new Book ('Advanced PHP', '1.2', '2004'),
        'Advanced PHP MVC' => new Book ('Advanced PHP MVC', '2.0', '2014'));
    }
    public function getBook ($name)
    {
        $allBooks = $this -> getBookList ();
        return $allBooks [$name];
    }
}
?>

In the above code of PHP MVC framework example, the ‘Book’ class is used to store the data of a book’s name, version and publishing year. The ‘model’ class is used to store the book’s details in the form of associative array with a method (getBook) to return the details of all the books data. It can  filter the book details by the ‘name’ attribute.

View

View defines what will be presented to the user. Controllers pass data to each view, to render in a specified format. View collect data from the user. This is the part where we use HTML mark up in the MVC application.

In PHP MVC framework, the view is responsible for all the display logic used to present data from the ‘model’ to the user. It is used to pass the user input to a controller using control events. In other words, a view is a part of application that involves the generation of the html and interaction with user.

View in PHP MVC Framework

In the example of ‘Book Selection’, the view presents data to a user with a combo-box and a submit button. It instantiates the ‘Model’ and ‘Controller’ classes to call the ‘invoke’ method of a controller and populates the combo-box with the retrieved data.

<?php
$model = new Model ();
$controller = new Controller ($model);
echo $controller -> output ();
$books= $controller -> invoke ();
if ($_SERVER['REQUEST_METHOD'] === "GET")
{
    if (isset ($_GET['book']))
    {
        echo "You selected " . $books -> name . " version: " . $books -> version . "
        Year of published: " . $books -> yearOfPublish ;
        exit;
    }
}
?>
<form method="GET" action="" >
<select name="book" >
    <?php
    foreach ($books as $x => $x_value)
    {
    echo '<option value="'.$x.'">'.$x.'</option>';
    }
    ?>
</select>
<input type="submit" value="Select">
</form>

In the above code the ‘output’ method of controller is called to generate the name of the application with the html heading tag. The ‘invoke’ method is called to retrieve the book’s information. A combo-box is filled with the returned book names. When we click on ‘submit’ button, a request is created with a book name selected in a combo-box to the same view, which displays details of selected book as output HTML page.

  • A view is some form of visualisation of the state of the model.
  • The view manages the graphical and/or textual output to the portion of the bitmapped display that is allocated to its application. Instead of a bitmapped display the view may generate HTML or PDF output.
  • The view renders the contents of a model. It accesses enterprise data through the model and specifies how that data should be presented.
  • The view is responsible for mapping graphics onto a device. A view typically has a one to one correspondence with a display surface and knows how to render to it. A view attaches to a model and renders its contents to the display surface.

Controller

Controller binds the whole pattern together. It is responsible to manipulate data. It controls which view to display based on the request of user and other factors and pass along the data that each view will need.

In PHP MVC framework, the controller takes an input from user as a request, processes and analyzes this input. it also initializes and invokes the model, takes the model response and sends it back to the respected view. So controller is a part of application that involves the logical processes of the application also called the business logic. It acts as a middle layer for views and models.

  • A controller offers facilities to change the state of the model. The controller interprets the mouse and keyboard inputs from the user, commanding the model and/or the view to change as appropriate.
  • A controller is the means by which the user interacts with the application. A controller accepts input from the user and instructs the model and view to perform actions based on that input. In effect, the controller is responsible for mapping end-user action to application response.
  • The controller translates interactions with the view into actions to be performed by the model. In a stand-alone GUI client, user interactions could be button clicks or menu selections, whereas in a Web application they appear as HTTP GET and POST requests. The actions performed by the model include activating business processes or changing the state of the model. Based on the user interactions and the outcome of the model actions, the controller responds by selecting an appropriate view.
  • The controller is the piece that manages user interaction with the model. It provides the mechanism by which changes are made to the state of the model.

Controller in PHP MVC

In the example of a ‘Book Selection’ controller, part of PHP MVC framework is represented by one class ‘Controller’. This class instantiates the model class and call the methods to retrieve the book’s information based on the request nature.

controller class

<?php
classController
{
  private $model;
  public function __construct (Model $model)
  {
  $this->model = $model;
  }
  public function invoke ()
  {
    if (!isset ($_GET['book']))
    {
      return $this->model->getBookList ();
    }
    else
    {
      return $this->model->getBook ($_GET['book']);
    }
  }
  public function output ()
  {
    return '<h1>'. $this->model->text.'</h1>';
  }
}
?>

In the above code of PHP MVC framework example, the ‘controller’ class instantiates the ‘model’ class using its constructor. Different methods of ‘model’ are called based on the request. When the page is loaded for the first time, a ‘getBookList’ method of ‘model’ is called to return all book details and ‘getBook’ is called when a ‘GET’ request is made, which results in a specific book detail based on the requested book name. The ‘output’ function of a controller is called to get the application name saved in ‘text’ property of ‘model’ class.

Like us on Facebook