Question

I have been reading into possible design patterns and have found the use of singletons always referred to as an anti-pattern.

I am currently using a singleton for the sole purpose of gathering configuration details based on my current build environment from a .ini file.

My singleton only has one public static endpoint that is a variadic function that takes in keys to reach a value:

$username = Config::Get("smpt", "username");

Internal to my Config class i maintain a protected instance that is setup on the first time of use and reused for further get calls.

The only internal state of the class is the setup of the internal re-used instance that does a unit of work to find which ini file to target, so creating a new instance every time feels unwise.

I have been finding this design very fast and useful but everything i read externally seems to warn against it, is what i'm doing considered bad? and is what i'm doing really called a singleton?

Was it helpful?

Solution

I have been finding this design very fast and useful but everything i read externally seems to warn against it, is what i'm doing considered bad?

Yes.

and is what i'm doing really called a singleton?

Yes, if you have a class and hide its constructor so that you may only have one instance of it then you have a singleton.

Other questions and sites do a good job at explaining why the singleton is an anti-pattern. tldr - it makes it hard to pick the source of your config at runtime, and it makes it impossible to test it (and often code that uses it) in parallel.

Licensed under: CC-BY-SA with attribution
scroll top