When should I use singleton pattern and static (static methods and static properties)?
I have read many blogs/ tutorials/ comments that always say that singleton pattern so I never use it.
But again, there are many php frameworks are using singletons, such as Laravel which is getting more and more popular these days.
For an example, in Laravel,
$app->singleton(
'Illuminate\Contracts\Http\Kernel',
'App\Http\Kernel'
);
$app->singleton(
'Illuminate\Contracts\Console\Kernel',
'App\Console\Kernel'
);
$app->singleton(
'Illuminate\Contracts\Debug\ExceptionHandler',
'App\Exceptions\Handler'
);
If you check it through, you can singleton is heavily used in Laravel (it seems). So what is going on?
Singleton is the first letter in STUPID that we should avoid as far as understand.
But I believe that some programmers will strongly disagree - Its the best way to do it in that situation - if you need to use them, use them. Simple as that.
So, in what situations then you should use singletons if you disagree with STUPID?
Also, in Laravel, you see lots of these,
$users = DB::table('users')->get();
It is either a singleton or a static method I guess (I am not very good at Laravel - just beginning to look into it).
It seems easy to use, but what about in testing, are they going to be difficult to test?
I see this method (DB::something(...)
) a lot in other framework as well. They seem not a good idea but many would disagree too I believe. So in what situations you should use static methods then?