views:

38

answers:

1

Ok im going to keep this really simple. Which method is the best for the likes of db handlers in an application: Singleton, Registry pattern, static configs class or config files.

Ive been reading about this and there seems to be a lot of contradictory ideas on this.

I understand that there wont be a one fits all solution but generally what is the best practice for this type of problem.

+1  A: 

Never use Singleton, this is nothing but a honking huge global variable whose initialization is bound to the lifetime of your process not the resource it manages.

What you want is an object injected into every scope that depends on it, in other words the pattern you are looking for is Dependency Injection.

For the simplest of apps, just use command-line parameters and a config object.

For slightly more complex apps, allow a default config object to be created from a config-file, and then modified by the command-line parameters.

For moderately more complex apps, integrate with your platform/language/OS native registry facility to provide the defaults.

For production applications, use an IoC-DI container and have the config/db/etc objects built externally to your application classes and injected at runtime.

The key is to avoid having a process-static config object, as this will interfere with testing, soft-restarts, and make migrating to more flexible configuration approaches more difficult.

Recurse
A small note here... you might want to avoid using the word "never" when discussing design patterns. For example the problem you stated about the Singleton lifetime is really not much of a problem in a lot of PHP web apps.
Manos Dilaverakis