CodeIgniter Forums
Namespace or function? - Printable Version

+- CodeIgniter Forums (https://forum.codeigniter.com)
+-- Forum: CodeIgniter 4 (https://forum.codeigniter.com/forum-28.html)
+--- Forum: CodeIgniter 4 Discussion (https://forum.codeigniter.com/forum-31.html)
+--- Thread: Namespace or function? (/thread-79696.html)



Namespace or function? - superior - 07-21-2021

Hi,

What do you prefer calling other classes, using the namespace like new \App\Model\ModelName or with the function model('App\Model\ModelName') ?
I haven't used this function before and am wondering what is the best approach to this, for me namespaces have more logic (in my head) but maybe someone has an answer for this?


RE: Namespace or function? - paulbalandan - 07-21-2021

Depends on your needs:

1. If you need an always fresh instance, you can use the "new" keyword.
2. If you need the shared instance, you can use the model function.
3. Alternative call for 1, you can also use the model function but passing false as 2nd argument.


RE: Namespace or function? - MGatner - 07-21-2021

I prefer to use the function in almost every case since I usually want the shared instance. I still tend to call it with the namespaced class name though to make my code easier to read, search, and analyze:

use App\Models\ModelName;

$object = model(ModelName::class)->first();


RE: Namespace or function? - superior - 07-21-2021

Thank you for the clarifycation on why to use the function, makes sense now!