0

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?

oasis
  • 197
  • 2
  • 13

1 Answers1

1

I would suggest that the best use of a singleton, which makes practical sense, is when you need to configure a resource that is costly to build.

In most cases, you'll find frameworks tend to create a singleton around database connections. This allows the resource of the database connection to be reused across the framework without having to rebuild the connection with the configurations every query.

The way laravel uses static methods like DB::table is that it will just be a wrapper around the singleton, or as they like to call it, an Inversion of Control Container (http://laravel.com/docs/4.2/ioc). The purpose there is to allow you to have a static interface for which you can change out the back-end singleton provider, should you need to use a different resource.

To answer the last part, the best purpose of a static method, would be either to run some computation over static or constant properties of the class which do not need an instance to exist (consider Java: when to use static methods).

Community
  • 1
  • 1
Brian Moore
  • 276
  • 1
  • 8
  • Thanks for the answer Brian. `when you need to configure a resource that is costly to build.` so what is costly to build? the db connection - just like Laravel? – oasis Mar 10 '15 at 13:22