4. Model - notafrancescodavid/webmvcframework GitHub Wiki

What is a model?

In an MVC software architecture, a model is a component that has the responsibility for data management. In other words, the model maintains a repository of data and provides the methods for data recording and retrieval. It is worthwhile to observe that the decomposition into the three components of an MVC architecture reflects the approach of divide et impera in which the controller assumes the role of coordinator that assigns the tasks of data management and data presentation to the model and view components respectively. In WebMVC, the instantiation of a model is similar to that of a controller or a view; in fact, it is sufficient to extend the framework\Model class. As an example, we can further discuss the problem of showing a list of people in a browser. In the previous section, the list was taken from the controller; while this could be convenient when the problem to solve is of small dimension (we could do without the model), it is more frequent the case where the data are managed by the model.

namespace models;

use framework\Model;

class UserList extends Model
{
    public function getUsers()
    {
        $users = array (
            array("FirstName" => "John", "LastName" => "Red"),
            array("FirstName" => "Mark", "LastName" => "White"),
            array("FirstName" => "Diana", "LastName" => "Brown"),
        );
        return $users;
    }
}

The controller must take into account the coordination of view and model following these steps:

  • Link the variable $this->view and $this->model to the corresponding class instances passing them to the constructor of the framework\Controller class
  • Use the instantiated model and view to retrieve and visualize the array of people through the getPeople() method

The controller retrieves the data from the model; then, calling the view, it arranges the presentation. To run the code, type the URL

localhost/user_list/show_users

Note that the code of UserList view and the corresponding template are unchanged.

<?php
namespace controllers;

use framework\Controller;
use models\UserList as UserListModel;
use views\UserList as UserListView;

class UserList extends Controller
{
    public function __construct() {
        $this->view =  new UserListView("user_list");
        $this->model = new UserListModel();	
        parent::__construct($this->view,$this->model);
    }
    
    public function showUsers() {
       $users = $this->getModel()->getUsers();
       $this->view->setUserBlock($users);
       $this->render();
    }
}

Database interaction

Having in mind the role of a model and how to use it in the MVC architecture, we can modify the previous example and retrieve the array of people from a database. Before we do so, it must be taken into account that:

  • WebMVC uses MySqli to interact with the database
  • The variable $this->sql, and the methods updateResultSet(), and getResultSet() are inherited from the framework\Model class
  • updateResultSet() executes a query previously stored in the variable $this->sql
  • getResultSet() returns the result set of the executed query by means of updateResultSet()
  • You must configure the file config\application.config.php. Specifically, you must modify the constants DBHOST, DBUSER, DBPASSWORD, DBNAME and DBPORT (an example of configuration here)

In this example, we modify the UserList classes by taking a set of people from a database. We assume the availability of a table called "people" containing the same data of the array $users shown above.

  • people -> table name
  • name -> the first attribute with the person name
  • surname -> the second attribute with the family name

For the sake of simplicity, we change only the methods of the previous classes:

//getPeople method of model\UserList class
public function getUsers() {
    $this->sql = "SELECT * FROM people";
    $this->updateResultSet();
    return $this->getResultSet();
}
//showPeople method of controllers\UserList class
public function showUsers() {
   $userResultSet = $this->model->getUsers();
   $this->view->setUserBlock($userResultSet);
   $this->render();
}
//setUserBlock method of views\UserList class
 public function setUserBlock($userResultSet) {
    $this->openBlock("Users");
    while ($people = $userResultSet->fetch_object()) {
       $this->setVar("FirstName", $people->name);
	   $this->setVar("LastName", $people->surname);
       $this->parseCurrentBlock();
    }
    $this->setBlock();
} 

What if you want to execute a SQL query that is different from a select? You can use the query method of the model. For example to insert a person called "George" in the people table you should use:

$this->query("insert into people(name) VALUES('George')").

The query method can execute every type of SQL operation (e.g. insert, update, select etc). This method can return:

  • false, if an error occurred
  • true, if no error occurred and the query is not a select
  • a result set if no error occurred and the query is a select

Summary

To run an MVC instance of an application we have seen how to:

  • create and run a controller and its methods calling them from the URL
  • create a views class linking it to a template file
  • substitute a dynamic variable to a placeholder inside a template
  • declare a block subject that must be transformed, for example in a list of values, within a template
  • created the model class taking the result set from a database of people.

Pay attention to the flow of operations when you define an MVC application in WebMVC:

  1. The URL calls a controller method (either with or without parameters)
  2. The controller runs the method and retrieves data from the model
  3. The data retrieved from the model are sent to the view by the controller
  4. The view organizes the data for the presentation.
  5. Finally, WebMVC sends the output of the execution to the user.

In the next page, we shall discuss how to organize your project into subsystems. See how to organize subsystems in your project.