T
T
topuserman2020-01-18 20:36:40
PHP
topuserman, 2020-01-18 20:36:40

Singleton alternative?

The fact that Singleton is an antipattern is known to everyone, and everyone will be able to tell about its negative sides.
I want to understand what are the alternatives for various tasks in which Singleton is often used.
For example, a task with a config class (or an implementation of the Request classes - which contains all the GET / POST data, etc.): I often see that it is implemented through a Singleton so that each object does not have to read and parse the configuration file (or data from the database) .
Is it efficient to solve such tasks through data caching?
There is also such a type of tasks (where Singleton helps out) - these are tasks with a connection to some data source (for example, connecting to a database).
I don't know how to provide this without Singleton. You can't cache the connection here.
The only option I know of is through dependency injection.
But I have no idea in what part of the application they do it. Need to create a database connection in the front-controller and place it in a DI container, and then use ? Or how ?
What other options, types of problems and their solutions are there?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
I
Ivan Vorobei, 2020-01-18
@ivanvorobei

Everyone knows that Singleton is an antipattern.

The problem is not the hammer, but the fact that inexperienced developers are trying to hammer the sugar in the morning lettuce. Singleton is a normal pattern. Connecting to a database is a good use case.
As with any other putter / instrument.

S
serginhold, 2020-01-18
@serginhold

The only option I know of is through dependency injection.
But I have no idea in what part of the application they do it. Need to create a database connection in the front-controller and place it in a DI container, and then use ? Or how ?

read something normal about di.
the container is created when the application starts,
in it you create an instance of the connection to the database:
$container->set('db', function () use ($container) {
    return new DbConnection($container->get('config')['db']);
});

then you transfer the connection to those services where it is needed:
$container->set('MyService', function () use ($container) {
    return new MyService($container->get('db'));
});

as an example where this happens: www.slimframework.com/docs/v4/concepts/di.html

A
Antonio Solo, 2020-01-19
@solotony

static ?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question