无需使用Global / Singleton即可在全球范围内使用数据库连接

I'm creating a new PHP application and want to make sure I get the ground work right to save any future problems. I know my application will have more than one class that will need a database connection (PDO) and after a long time scouring the internet i can't find a definitive solution.

I like the singleton design pattern personally, but there are a lot of people out there that say singletons in general should be avoided at all costs. These people, however, don't give a specific solution to this problem.

I understand that an application may need more than one database connection but could i not create a singleton that contained each required DB connection (i.e. DB::getInst('conn1')->query(); )?

Is it a case of having to pass round the PDO (or PDO wrapper) object to every class that may need it? I've done this before found it annoying keeping track of it.

I personally thing a singleton (or a multiton, if you need several DB connections) is fine for such an usage.

But if you do not want to use it, you should then take a look at the Registry pattern.

This way, you can have your database class instance(s) available for all your application's classes, without having to pass an additional parameter each time (which is very ugly, IMHO).

but could i not create a singleton that contained each required DB connection (i.e. DB::getInst('conn1')->query(); )?

you can, it's called multiton pattern