简体   繁体   中英

CodeIgniter 4 how to load a model in the controller?

First of all, I am having very little knowledge of CodeIgniter 3 and now I am first time using the new CodeIgniter 4. For the HMVC module building, I was using MX_Controller in CI3. Now when I came to know the CI4 is by default supporting HMVC I am trying to make use of it. When I try to port my first module I am getting an error in the Controller about the constructor.

  1. How can I load my model in this controller?

  2. Can't I load my model in the constructor straight away?

Template.php [Controller]

<?php
namespace Modules\Template\Controllers; // sPiDeR adder namespace for CI4 support
//defined('BASEPATH') OR exit('No direct script access allowed');
class Template extends \CodeIgniter\Controller { // Using CI controller instead of MX Controller

    public function __construct()
    {
        parent::__construct();
        $this->load->model(array(
            'template_model'
        ));
                
    }

    public function layout($data)
    {
        $id = $this->session->userdata('id');
        $data['notifications'] = $this->template_model->notifications($id);
        $data['quick_messages'] = $this->template_model->messages($id);
        $data['setting'] = $this->template_model->setting();
        $this->load->view('layout', $data);
        //echo view('layout', $data); //sPiDeR update syntax change
    }

    public function login($data)
    {
      $data['setting'] = $this->template_model->setting();
      $this->load->view('login', $data);
    //echo view('login', $data); //sPiDeR update syntax change
    }

}

Error I am getting in Debugger

在此处输入图像描述

Please use model like that its working surely.

use App\Models\Model1;
use App\Models\Model2;
    class Myclass extends Backendcontroller
    {

        public function __construct()
        {
            $this->Model1 = new Model1();
            $this->Model2 = new Model2();
        }


$foo = $this->Model3->where('bar', $bar)->findAll();

I'll recommend using Upgrading from 3.x to 4.x guide while you migrate your app from CI3 to CI4. All the changes you might require to convert your app from version 3 to 4 are explained in it.

Steps for upgrading models include what you need. Quoting only part relevant to question:

  1. Instead of CI3's $this->load->model(x); , you would now use $this->x = new X(); , following namespaced conventions for your component. Alternatively, you can use the model function: $this->x = model('X') ;.

You can load models from within the constructor if you follow one of these approaches.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM