Best practices for loading models in controllers in CI 4? |
Hello
In CI 3 I have loaded the models that I need in my controllers like this: Code: public function __construct() Now, in CI 4, I am using the following code: Code: use App\Models\SomeModel; 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.
Code: use App\Models\SomeModel as SomeModel; 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
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');
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.
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; PHP Code: class Myclass extends Backendcontroller |
Welcome Guest, Not a member yet? Register Sign In |