0

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?

  • Do you writing tests for your application? – Fabio Feb 16 at 17:06
2

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.

  • If my singleton is wrapping another class that can be instantiated and digested separately in unit testing is that any better? – Necro Feb 14 at 5:36
  • @Necro - maybe, can you run tests against the various things that depend on the config with different configs in parallel? – Telastyn Feb 14 at 5:46
  • I can test various versions of config in parallel separately but in my actual code the config singleton is a blackbox bringing back .ini files based on what runtime environment is being started for test or production for example. The things that depend on Config all refer to the singleton implementation of it. But they could just as easily make their own instance to use, but its more setup and management work for the new object lifecycle. – Necro Feb 14 at 6:06

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.