Welcome Guest, Not a member yet? Register   Sign In
General use class: static or not?
#1

I have this generic class with some small functions to be used by the whole application.

I would like to know what is considered a 'better practice' in this case: make the methods as static and call them directly or instantiate the class into the controller?

Huh 

Thanks!
Recovering the wasted time...
Reply
#2

@YanKleber,

Is this for CI3 or CI4?
Reply
#3

(This post was last modified: 05-06-2020, 02:30 PM by YanKleber.)

(05-06-2020, 02:28 PM)php_rocs Wrote: @YanKleber,

Is this for CI3 or CI4?

It's CI4. I thought that being basically plain PHP it wouldn't matter, sorry.
Recovering the wasted time...
Reply
#4

(This post was last modified: 05-06-2020, 02:55 PM by php_rocs.)

@YanKleber,

While yes they both are based on PHP, there are differences between CI3 and CI4. Here is some documentation that may assist you https://codeigniter.com/user_guide/gener...de-modules.
Reply
#5

I see... well I am not sweating too much about this... I tested and both methods work without any noticeable difference. I just was imagining if one of them could be considered more "correct". Thanks!

Cool
Recovering the wasted time...
Reply
#6

(This post was last modified: 05-07-2020, 03:07 PM by nicojmb.)

(05-07-2020, 08:53 AM)YanKleber Wrote: I see... well I am not sweating too much about this... I tested and both methods work without any noticeable difference. I just was imagining if one of them could be considered more "correct". Thanks!

Cool

Hi, if is CI4 make your class as service and you call directly like this:

PHP Code:
$class = \Config\Services::yourClass();
$class->yourVariable;
$class->yourMethod();
or
$variable = \Config\Services::yourClass()->yourVariable;
or
$method = \Config\Services::yourClass()->yourMethod(); 

Here are docs:

https://codeigniter4.github.io/userguide...vices.html
Reply
#7

Cool nicojmb I'll take a look, as well as the docs pointed by php_rocs either!

Smile
Recovering the wasted time...
Reply
#8

@YanKleber,

Here is some reading that discusses the differences of CI3 and CI4 (more focus on CI4): https://codeigniter.com/user_guide/insta...e_4xx.html
Reply




Theme © iAndrew 2016 - Forum software by © MyBB