Welcome Guest, Not a member yet? Register   Sign In
Best practices for loading models in controllers in CI 4?
#1

Hello

In CI 3 I have loaded the models that I need in my controllers like this:

Code:
public function __construct()
    {
        parent::__construct();
        $this->load->model('Some_model');
        $this->load->model('Some_other_model');
    }   // End of constructor function

Now, in CI 4, I am using the following code:

Code:
use App\Models\SomeModel;
use App\Models\SomeotherModel;
    class Myclass extends Backendcontroller
    {

        public function __construct()
        {
            $this->someModel = new SomeModel();
            $this->someOtherModel = new SomeotherModel();
        }


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

My question is: Can this be considered best practice? Can anyone point better way for loading models that I need to use in my controllers? 

Any advice would be deeply appreciated.
Reply
#2

Code:
use App\Models\SomeModel as SomeModel;
use App\Models\SomeotherModel as SomeotherModel;
    class Myclass extends Backendcontroller
    {

        public function __construct()
        {
            $this->someModel = new SomeModel();
            $this->someOtherModel = new SomeotherModel();
        }


use App\Models\SomeModel as SomeModel;
use App\Models\SomeotherModel as SomeotherModel;

Learning CI4 from my works, from errors and how to fix bugs in the community

Love CI & Thanks CI Teams

Reply
#3

No need to use "as" since the names of the models do not clash with the controller class name. Anyway, your approach of using the "new" keyword is one of the approaches possible. You can also use the "model()" function if you want to load the same instance of your model everywhere you need it.

In your code, if you will be using the model function you can also skip the use statements for the models.

You can use either:

$this->someModel = model('Some_model');
$this->someOtherModel = model('Some_other_model');

If you want, you can also use the full qualified name if your models are namespaced.
model('App\Models\SomeModel');
Reply
#4

Hi

Thanks for the suggestions. I must admit  that I skim trough the documentation and that I may have miss something. Hopefully this post may help someone else too.

I appreciate your time.
Reply
#5

I think it's good place to ask here about one other thing.

What if I want to use some model in only one function. It makes any diffrence to performance if I write:
PHP Code:
use App\Models\SomeModel;
class 
Myclass extends Backendcontroller
{

    public function testfunction()
    {
        $var = new SomeModel();
    }

or
PHP Code:
class Myclass extends Backendcontroller
{

    public function testfunction()
    {
        $var = new \App\Models\SomeModel();
    }

Reply




Theme © iAndrew 2016 - Forum software by © MyBB