Is there a use-case for singletons with database access in PHP?

后端 未结 11 1824
名媛妹妹
名媛妹妹 2020-11-21 06:44

I access my MySQL database via PDO. I\'m setting up access to the database, and my first attempt was to use the following:

The first thing I thought of is glob

11条回答
  •  情歌与酒
    2020-11-21 07:21

    Consider simply how your solution differs from the one presented in the PHP docs. In fact, there is just one "small" difference: your solution provides callers of the getter with a PDO instance, while the one in the docs provides callers of Database::singleton with a Database instance (they then use the getter on that to get a PDO instance).

    So what conclusion do we reach?

    • In the documentation code, callers get a Database instance. The Database class may expose (in fact, it should expose if you 're going to all this trouble) a richer or higher-level interface than the PDO object it wraps.
    • If you change your implementation to return another (richer) type than PDO, then the two implementations are equivalent. There's no gain to be had from following the manual implementation.

    On the practical side, Singleton is a pretty controversial pattern. This is mainly because:

    • It's overused. Novice programmers grok Singleton much easier than they grok other patterns. They then go on to apply their newfound knowledge everywhere, even if the problem at hand can be solved better without Singleton (when you 're holding a hammer, everything looks like a nail).
    • Depending on the programming language, implementing a Singleton in an airtight, non-leaky manner can prove to be a titanic task (especially if we have advanced scenarios: a singleton depending on another singleton, singletons that can be destroyed and re-created, etc). Just try to search for "the definitive" Singleton implementation in C++, I dare you (I own Andrei Alexandrescu's groundbreaking Modern C++ Design, which documents much of the mess).
    • It imposes additional workload both when coding the Singleton and when writing code to access it, workload which you can do without by following a few self-imposed constraints on what you try to do with your program variables.

    So, as a final conclusion: your singleton is just fine. Not using Singleton at all is just fine most of the time as well.

提交回复
热议问题