• 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
CodeIgniter 4 Models preloading

#1
Hello. I need help. I am using CodeIgniter 4 and trying to preload model logas_model in BaseController.php: http://prntscr.com/r90208
And then, in other controller, which extends Controller, I am trying to use that preloaded model by using it's function but it is not working. http://prntscr.com/r903xu
What am I doing wrong?
Reply

#2
You should preload components (like models, etc.) by using initController() as demonstrated here.

There is a controller named BaseController distributed with the framework that is included exactly for the purpose of doing what you want. Look closely at how initController() is defined in app\Controllers\BaseController.

PHP Code:
public function initController(\CodeIgniter\HTTP\RequestInterface $request, \CodeIgniter\HTTP\ResponseInterface $response, \Psr\Log\LoggerInterface $logger)
{
 
// Do Not Edit This Line
 
parent::initController($request$response$logger);

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


Put your model loading in the commented section near the bottom. (Oh, and remove the comments.) It might look like this

PHP Code:
public function initController(\CodeIgniter\HTTP\RequestInterface $request, \CodeIgniter\HTTP\ResponseInterface $response, \Psr\Log\LoggerInterface $logger)
{
 
// Do Not Edit This Line
 
parent::initController($request$response$logger);

 
//--------------------------------------------------------------------
 // Preload any models, libraries, etc, here.
 //--------------------------------------------------------------------

        $this->vartotojai =  new vartotojai_model();


Then extend any controllers that need this model from BaseController

PHP Code:
namespace App\Controllers;

use 
CodeIgniter\Controller;

class 
NewController extends BaseController
{
        //use $this->vartotojai as needed


On a side-note: Please don't use Lightshot or the like to show code. Instead, copy & paste and surround the lines of code with [php] ...lines of code... [\php] tags. Thanks.
Reply


Digg   Delicious   Reddit   Facebook   Twitter   StumbleUpon  


  Theme © 2014 iAndrew  
Powered By MyBB, © 2002-2020 MyBB Group.