Answer the question
In order to leave comments, you need to log in
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
Everyone knows that Singleton is an antipattern.
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 ?
$container->set('db', function () use ($container) {
return new DbConnection($container->get('config')['db']);
});
$container->set('MyService', function () use ($container) {
return new MyService($container->get('db'));
});
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question