Skip to content

3.3 Modules | Models

GrumpyCrouton edited this page Oct 12, 2022 · 7 revisions

Models are the layer of the module which is meant to do all of the database communications and work with data. You load them in your controller, and use the controller to call specific methods inside the model. There is no harm in separating logic into many different models.

Creating a Model

Inside your module folder, create a new folder called "models". Inside this folder create a new file called "CustomModel.php". The name of the model does not matter, I'm using this as an example.

Be sure to change {module_name} to the name of your module folder.

CustomModel.php:

<?php
namespace modules\{module_name}\models;
class CustomModel extends \Model {
	
	public function example() {
		return "This is an example";
	}
	
}

Using a Model

In controller.php, load a model in any method like this:

/*
 * model_file_name
 * The name of the file of the model you want to load. Do not specify extension.
 *
 * module_override
 * Used to load models from different modules. If not specified, current module will be used
 */
$custom_model = $this->model(string model_file_name, (optional)string module_override);
//OR
$custom_model = $this->loadModel(string model_file_name, (optional)string module_override);

//use $CustomModel
$return = $custom_model->example(); //$return = "This is an example"

Then, you can access methods of that model from the controller. Utilize this to keep your main controller cleaner, by handing off control to the model. It's main purpose is communicating with the database, but can also be used to encapsulate all of the data processing required to communicate with the database.

Common model uses:

  • Direct the model to get some information from the database
  • Direct the model to update some information in the database
  • Process user submitted data to eventually be updated in the database

Utilizing GrumpyPDO

In your model, it's easy to do database queries using GrumpyPDO, simply call it by using $this->db.

For example, this method can be used in a Model to get all records from a database table called "records".

public function fetch_records() {
	return $this->db->all("SELECT * FROM records");
}

This functionality could be pretty easily swapped to your preferred database wrapper by changing the assignment of db in index.php.