CodeIgniter Forums

Full Version: BaseController load, use model example
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I have a model that performs some operations in my database. We'll call it "Somemodel". There's a method I want to use called "somemethod($value)" in the Somemodel model. I'd like to include this model and call that method in every controller. I know that I can modify the BaseController, and all my controllers should extend BaseController. Can someone show me an example of what that looks like? The documentation shows using a Session service.  So, what does the code look like to load one of my models?

// Do Not Edit This Line
parent::initController($request, $response, $logger);

// Preload any models, libraries, etc, here.
// E.g.:
// $this->session = \Config\Services::session();

$session = \Config\Services::session($config); // I like this!

// How do I load one of my models and use a method? What does that code look like?
There is a helper that you can use that makes it a lot simpler.

PHP Code:
// Create a new class manually
$userModel = new \App\Models\UserModel();

// Create a new class with the model function
$userModel model('App\Models\UserModel'false);

// Create a shared instance of the model
$userModel model('App\Models\UserModel');

// Create shared instance with a supplied database connection
// When no namespace is given, it will search through all namespaces
// the system knows about and attempt to located the UserModel class.
$db db_connect('custom');
$userModel model('UserModel'true$db); 

CodeIgniter 4 User Guide - Using CodeIgniter’s Model
Thank you, InsiteFX! That was exactly what I needed.
(I tried to "+Rate" your post, but Chrome wouldn't have it).
I greatly appreciate your response.