How it works and why I need the Singleton pattern.

It bothers that everyone is scolded and called it an anti-pattern, saying that it violates the concept of OOP, which is not tested by unit testing without the use of hacks and now it is being tried not to be used. Okay.

And what can it be replaced with then, if you need to do exactly what you came up with for Singleton? In my case:

  • you just need to pull out of the class settings for the system anywhere
  • guaranteed to create only one object of this class

Or is it just a lie, those who do not understand how and where to use this pattern?

Where to dig something? Which way?

1 answer 1

Found, the solution is simple: to make a single class from singletona that does not violate the principles of OOP (in my case with the system settings), but to create its object using an IoC container, for example: "Pimple":

Объявление сервисов «Синглтонов»: 

By default, every time Pimple is called, it returns a new service object. If one instance is required for the entire application , all you need to do is wrap the declaration in the share () method:

 $IoC['object_name'] = $IoC->share(function ($c) { return new Config($c['class_name']); }); 

BUT, as it was before, in versions 1.x , now the Pimple developers have removed the share () method. Although no one will forbid you to use the old version 1.x, it is on the githab (link is below).

Although in the new versions (3.x) of this container there is no share () method, but still it is better to use an IoC container to manage dependencies than Singleton:

 // Регистрируем зависимости через IoC контейнер "Pimple": $IoC = new Container(); // Объявление сервисов: $IoC['obj_conf'] = function ($c) { return new Config($c['Config']); }; 

References:

  1. https://habrahabr.ru/post/199296/
  2. http://pimple.sensiolabs.org/
  3. https://github.com/silexphp/Pimple/blob/1.1/lib/Pimple.php - version 1.x

And further:

There are quite a lot of IoC containers, use what is convenient for you: