Search code examples
codeigniter-4

Create/Include a modell for the whole controller in Codeigniter4


i do my first steps in CI4.

Is there a way to define a modell into a controller for each functions of a controller one at one time?

At the moment i have to add the modell for each function as new like this

public function myfunction(){
   $myModel = new \App\Models\MyModel();
}
public function myfunction_two(){
   $myModel = new \App\Models\MyModel();
}
...

Update

Based on the answear i try this

class controllertwo extends BaseController
{
    private $myModel;
    public function __construct()
    {
        //Add some Models we need in this controller?
        $this->myModel= new \App\Models\myModel();
        //$this->myModel= new myModel();
    }

...

The Codeigniter Errorconsole said "Use of undefined constant int - assumed 'int' (this will throw an Error in a future version of PHP) " and markes this line "$this->myModel= new \App\Models\myModel();"

What i do wrong? Or is it not the best way to include a modell for all functions inside a controller?


Solution

  • You can declare it as a private variable in the controller as follow :

    private $model;
    

    Then set it in the constructor as follow:

    public function __construct()
        {
            $this->model = new \App\Models\MyModel();
      }
    

    Then simply refer to them in your methods as below:

    public function myfunction(){
       $this->model ...
    }
    public function myfunction_two(){
        $this->model ...
    }