Categories
MVC PHP

An Introduction to Models

To complete the PHP MVC trio, we must take a look at Model classes. Model classes provide data access and modification functionality to MVC applications, regardless of what the data source is. In other words, the way that the Model classes are used should not reveal to the Controller classes what type of data storage medium is being used. All we wish to provide to the Controller classes is an interface to create, read, delete, and update information. And, by default, our Model classes will perform these CRUD operations in databases.

A Model Base Class

As was done with the Controller base class to provide core functionality to Controller classes, we wish to provide the base functionality to Model classes through a Model base class. In our case, this base functionality will be to connect to a MySQL-compatible database. So, to /app/core, we add Model.php:

class Model{
  protected static $_connection = null;
  public function __construct(){
    if(self::$_connection == null){
      $user = 'root';
      $password = '';
      $host = 'localhost';
      $DBName = 'test';
      self::$_connection =  new PDO("mysql:host=$host;dbname=$DBName", $user, $password);
    }
  }
}

In the above, we declare and initialize a static attribute $_connection. Static attributes are attributes of the class; only one instance of this attribute exists for the entire set of all objects in this class, i.e., one $_connection for all objects deriving from class Model. Then, one the first run of the constructor for the class, when $_connection is null, it is set to a PDO object connected to a MySQL database, called test, hosted on localhost (the same computer as the one running the PHP, which is your computer if you are running XAMPP locally). The connection is done through the ‘root’ user which has no password, by default, in the XAMPP MySQL installation. You should definitely change these settings!

Let’s not forget to adjust dependencies… modify your app/init.php file to add the new Model class:

<?php
  require_once 'core/App.php';
  require_once 'core/Controller.php';
  require_once 'core/Model.php';
?>

Building a Model Subclass

For each table in our database, we will wish to build one Model class. We say that these are Model classes, and this is semantically true. In this specific example, they are effectively subclasses of our Model class. To continue our example, we build a model for Item in the Item.php file in the /app/models folder:

class Item extends Model{
  var $name;
  public function get(){
    $SQL = 'SELECT * FROM ITEM';
    $stmt = self::$_connection->prepare($SQL);
    $stmt->execute();
    $stmt->setFetchMode(PDO::FETCH_CLASS, 'Item');
    return $stmt->fetchAll();
  }
}

In the Item model, we define a $name attribute, such that all objects of this class have this property. Then, the get() method is declared to run a SELECT * FROM ITEM query in the database. The query is defined, then prepared (this will become more useful further along as you read), to then be executed. Then, since SELECT is a read command, there will be records to fetch, we set the fetch mode to return objects of the Item class (this class). Finally, we return an array of Item objects, each representing the records read from the database.

The Database to Match

To complete this example, we must create an Item table in our test database, and have the records have item_id (for instance) and name fields. To accomplish this, go back to your xampp control panel, if this is what you are using, and on the MySQL line, click Start and, once MySQL is highlighted green, click Admin; this will open an instance of phMyAdmin.

If you have a test database in the left menu, click on it (otherwise, you certainly know how to add one). You should be prompted to add a table, if not, expand the test database in the left structure and click on New table.

At the top left, name the table Item. Let’s add the item_id field first by typing that name in the Name column and selecting the checkbox in the A_I colunm (if anything pops up, just click OK). Now let’s add the name of the item by adding name on the following line’s Name column, in the type column, select VARCHAR, in the Size colunm, enter the value 50. Click Save at the bottom right.

Now let’s add test data to the table. Click the Insert tab in the top tabs row. For example, insert ‘milk’ and ‘cookies’ in the Value column for the name field. Click one of the execute buttons on the right.

Making it Work

If you followed along with the posts and implemented the HomeController class as in Controller Classes and An Introduction to Views, all script elements can be called through your browser at http://localhost/ and display your items from the database Item table.

By Michel

My name is Michel Paquette. I currently teach my students how to create data-driven Web applications at Vanier College, in Montreal.

My GitHub page contains a few examples of Web applications. Also consult my YouTube channels: @CSTutoringDotCa and @MichelPaquette.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.