I understand that we could autoload or load models in the constructor and use them all through the class in earlier versions of codeigniter like below:
//Declaring the variable
$this->load->model('model_name');
//Using it through the controller
$this->model_name->function();
But in codeigniter 4, is there an easier way of defining a model variable once in a Controller. The current way i know of doing that is :
//Declaring the variable
$model_var = new ModelName();
//Using it through the controller
????????
But as far as i have tried looking, i have to do the initializing in every function.
The easiest thing to do is create a property for the controller to hold an instance of the model.
CI v4 relies on an initializer function instead of a constructor to set up properties and the like. So creating something like this would follow "best practice" for a simple controller in a simple app.
<?php
namespace App\Controllers;
/**
* Class SomeController
*
*/
use CodeIgniter\Controller;
class SomeController extends Controller
{
/**
* @var ModelName instance
*/
// $modelVar; ```edited - will throw a php syntax error```
protected $modelVar; ```this works```
/**
* Initializer
*/
public function initController(\CodeIgniter\HTTP\RequestInterface $request, \CodeIgniter\HTTP\ResponseInterface $response, \Psr\Log\LoggerInterface $logger)
{
parent::initController($request, $response, $logger);
// Load the model
$this->modelVar = new ModelName();
}
}
For your convenience, CI supplies /app/Controllers/BaseController.php
that the above example used in part.
The idea behind BaseController
was to provide a class that could be used to load resources (classes, helpers, etc) that EVERY controller in the application would need. Then each controller would extend from BaseController
. The above example assumes that there isn't a need for anything else, which in real-life is unrealistic. So the above could extend BaseController
too if there were a need.