php singleton database connection, is this code bad practice?

前端 未结 4 1797
天命终不由人
天命终不由人 2020-12-06 20:18

I\'m trying to create a simple to use singleton class to connect to mysql database and do queries, the code works fine and i haven\'t had any problems with it, but since I\'

4条回答
  •  误落风尘
    2020-12-06 20:46

    Singletons are bad news.

    • They introduce global state into a program. Most programmers should be familiar with why global state is bad.
    • They introduce tight coupling between the singleton and any class that uses it. This means you can't reuse the classes in question without reusing the singleton too.
    • They make unit testing of classes that depend on the singleton problematic because you can't easily replace the singleton with a mock.
    • They encourage a coding style where classes attempt to resolve their own dependencies. This is bad because it can reduce clarity regarding what dependencies the class has.
    • PHP has a Share Nothing Architecture, meaning that PHP singletons aren't really singletons at all, there can be multiple instances alive at any one time (one per open request).
    • What happens if you suddenly discover at some later date that you actually need more than one of the resource that's being provided by the singleton? It's a more common scenario than you might think

    You're better off looking at dependency-injection instead, as it resolves the above issues.

提交回复
热议问题