Welcome Guest, Not a member yet? Register   Sign In
CodeIgniter 4 Models preloading
#1

Hello. I need help. I am using CodeIgniter 4 and trying to preload model logas_model in BaseController.php: [font=Helvetica, Arial, sans-serif]http://prntscr.com/r90208[/font]
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. [font=Helvetica, Arial, sans-serif]http://prntscr.com/r903xu[/font]
What am I doing wrong?
Reply
#2

(This post was last modified: 02-28-2020, 02:47 PM by dave friend.)

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




Theme © iAndrew 2016 - Forum software by © MyBB